Qwe500 Qwe500 - 3 months ago 17
C++ Question

Are global or local variables more efficient?

It's very common in games to calculate the time it took to render the last frame (delta time) in order to produce smooth movement, timers, etc.

One way of doing this would be to declare 3 global variables:

float deltaTime, currentTime, elapsedTime;


and then calculate the delta time at the start of the game loop:

currentTime = getTime();
deltaTime = currentTime - elapsedTime;
elapsedTime = currentTime;


(where getTime() is a function that return the time since the program started)

Another way of doing it would be to declare deltaTime and currentTime as local variables:

float currentTime = glfwGetTime();
float deltaTime = currentTime - elapsedTime;
elapsedTime = currentTime;


If my understanding is correct, the compiler then has to deallocate the memory of the variables at the end of the loop and, in the next iteration of the loop, reallocate it all over again causing it to be more inefficient than just declaring global variables.

Is this correct or is there some other stuff automagically happening in the background that I'm not aware of?

Answer

If my understanding is correct, the compiler then has to deallocate the memory of the variables at the end of the loop and, in the next iteration of the loop, reallocate it all over again causing it to be more inefficient than just declaring global variables.

That's not true.

Compilers don't allocate and deallocate memory for local variables in a loop. Memory for local variables in a functions is, usually, allocated when the stack frame for a function is created.

The variables are initialized in each run of the loop.

If the variable is a class type that has a constructor and destructor, they will be called in each run of the loop, which could be expensive depending on what happens in the constructor and the destructor, the number of times the loop is run.

For a float type, there shouldn't be any overhead due to use of a local variable in a loop. I will be very surprised if there is any.

Comments