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?
Global variables are really slow, in addition to all the other reasons not to use them.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With