Are global variables faster than local variables in C?

7.1k views Asked by At

I had a couple thoughts on this. The first is that allocating global variables may be faster, since they are only allocated once, at the time the program is first spawned, whereas local variables must be allocated every time a function is called. My second thought is that since local variables are on the stack, they are accessed through the base pointer register, so the value stored in the base pointer must be decremented every time a local variable is accessed; global variables are accessed directly through their static addresses in the data segment. Is my thinking accurate?

1

There are 1 answers

4
Leon Carlo Valencia On BEST ANSWER

It's rather inaccurate.

If you study computer architecture, you'll find out that the fastest storage are the registers, followed by the caches, followed by the RAM. The thing about local variables is that the compiler optimizes them to be allocated from the registers if possible, or from the cache if not. This is why local variables are faster.

For embedded systems, sure it might be possible to compile to a tiny memory model in which case your data segment may possibly fit into a modern controller's SRAM cache. But in such cases, your local variable usage would also be very tight such that they are probably operating entirely on registers.

Conclusion: In most cases, local variables will be faster than global variables.