C Question

Performance: should I use a global variable in a function which gets called often?

First off, let me get of my chest the fact that I'm a greenhorn trying to do things the right way which means I get into a contradiction about what is the right way every now and then.

I am modifying a driver for a peripheral which contains a function - lets call it

. In the function I have a timestamp variable so the function loops for a specified amount of time.

So, should I declare the variable global (that way it is always in memory and no time is lost for declaring it each time the function runs) or do I leave the variable local to the function context (and avoid a bad design pattern with global variables)?

Please bear in mind that the function can be called multiple times per milisecond.

Answer Source

Speed of execution shouldn't be significantly different for a local vs. a global variable. The only real difference is where the variable lives. Local variables are allocated on the stack, global variables are in a different memory segment. It is true that local variables are allocated every time you enter a routine, but allocating memory is a single instruction to move the stack pointer.

There are much more important considerations when deciding if a variable should be global or local.