Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are global variables faster than local variables in C? [closed]

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?

like image 665
user628544 Avatar asked Dec 14 '16 16:12

user628544


People also ask

Are global variables slow in C?

Global variables are really slow, in addition to all the other reasons not to use them.

Do global variables make programs run faster?

Using globals is usually slower than passing parameters for two reasons: Parameter passing is implemented better now. Modern CPUs pass their parameters in registers, so reading a value from a function's parameter list is faster than a memory load operation.

What are the advantages of global variable in C?

Advantages of Global VariableGlobal variables can be accessed by all the functions present in the program. Only a one-time declaration is required. Global variables are very useful if all the functions are accessing the same data.

Are global variables fast?

A global variable is always the fastest reference, BUT it is utterly unprotected and open to whatever mischief any hacker may choose to make of it. In many shops, global variables are utterly banned, with the exception of constants.


1 Answers

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.

like image 57
Leon Carlo Valencia Avatar answered Sep 21 '22 23:09

Leon Carlo Valencia