🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Allocating variables

Started by
1 comment, last by Qoy 24 years, 6 months ago
Allocating variables on a stack frame is just a subtraction, so one operation per function. About 1/3 of a cycle on current processors.

Don't worry about it.

Advertisement
I am writing a bitmap loading function, and as I was optomizing it, I was thinking of how a lot of the time you would create a variable to hold a value, instead of having to calculate it every time through a loop, and I was wondering, just how fast is allocating memory for a variable? I don't mean with new or malloc, I just mean declaring a variable. It seems to me that it would be slower than most operations, but I was just wondering...

------------------
http://qoy.tripod.com

I assume you're doing something like this :-

while (...)
{
int i;
...
}

and you want to know how much processor time will be used for the declaration of the variable 'i' within the loop? Assuming that is your question...

If it's a tight loop then the variable 'i' will (hopefully) end up being put in a machine register. If this is the case then there is no overhead. If the loop is quite complicated and many variables are used in it then there won't be enough registers. In this case, variables are "spilled" into stack memory.

The variables are then transferred netween memory and registers as necessary, using an instruction like

mov eax, [ebp-24] or mov [ebp-24], eax

If you ask your compiler to generate a disassembly then you can see exactly which variables end up on the stack, by looking for instructions of this type. To reduce the number of variables that end up on the stack you have to minimize the number of variables accessed within the loop.

Interestingly, moving the variable declaration outside the loop does not make the loop any faster. The compiler's optimizer can easily see what the true live range of each variable is. Put your variable declarations in the place that make the code most clear!

This topic is closed to new replies.

Advertisement