Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


Allocating variables

This topic is 6876 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post

Link to post
Share on other sites
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!

Share this post

Link to post
Share on other sites
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...


Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!