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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
staticvariables. I would recommend using these instead, as otherwise you’ll end up polluting the global namespace.