Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, will working with global variables help the stack?

Tags:

performance

c

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?

like image 469
lindelof Avatar asked Jan 21 '23 14:01

lindelof


1 Answers

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.

like image 75
bdonlan Avatar answered Jan 29 '23 10:01

bdonlan