Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What are the performance and memory differences between a local array and a static const local array?

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading