I am trying to decide whether to use
int x[] = {/*some numbers*/};
or
static const int x[] = {/*some numbers*/};
My understanding is that the first version will remake the array every function call, which seems wasteful, while the second will make a global variable accessible only by the function, and the memory distance might be less performant. (const is just there for decoration in C, and to show you that the numbers won’t change).
I first made the array in global scope, but then I thought it might be better to limit the scope. Ofcourse, maybe the best thing to do would be to just do it normal and have the array remade every time. I don’t know.
>Solution :
Yes static const will likely perform better and never worse than the alternative without qualifiers. Without them there’s a chance that the data will get loaded onto the stack at each function call.
Reducing the scope as much as possible is good practice.
const is just there for decoration in C, and to show you that the numbers won’t change
This isn’t true, especially not on ROM-based systems like microcontrollers. On those systems, const often makes the difference between RAM allocation and flash allocation.
Furthermore, there’s a bunch of more subtle things related to const such as pointer aliasing decisions made by the compiler, meaning it can improve performance in some situations. Check out my recent answer at https://stackoverflow.com/a/75854539/584518. There are several situations in those examples where static and/or const improves performance.