No I'm really serious.
I've just witnessed someone move variables local to a function up to global status, with the commit message "Relieve the stack".
Is there really some rationale towards doing this sort of thing?
First, putting variables in global variables doesn't improve CPU usage directly. Stack initialization is generally a single add/subtract at function entry/exit, independent of stack frame size.
However, if the function requires a very large working set, it's better to put it in something other than stack; the stack's size is usually rather limited. The usual choice is the heap; however this does take time to allocate and free, and so if you're going to be calling the function frequently it can be expensive. It's also a problem on embedded systems, where they may not have a proper heap implementation.
So if heap is a problem, globals can be a solution. However, they have their own downsides - in particular, you don't want to have multiple threads messing with the global data at the same time, nor can you recurse through this function without taking a lot of care, or the recursed bits may corrupt the earlier calls to the function.
So it's a technique which, in some cases, can be helpful. I wouldn't recommend using it as a first choice however, because of threading issues.
Also, for what it's worth, you can get the same memory effects with static
variables. I would recommend using these instead, as otherwise you'll end up polluting the global namespace.
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