Sign in to follow this  
Slaru

Class member or stack variable

Recommended Posts

Slaru    222
Hello, I was wondering what would be more efficient. I have a class, and in there is a function that is called very often, such as every frame of a game. Would it be more efficient to create a stack variable for the function every time it is called, or to just make that variable a class member? I think I should just make it a class member, but that is just my guess since if I created it on the stack, there would be the overhead of creating it every time the function is called. Any thoughts? Slaru

Share this post


Link to post
Share on other sites
Palidine    1315
if the variable doesn't need to remember anything between function calls put it on the stack. if it does need to remember values between function calls make it a member variable. the speed of allocating a single variable on the stack WILL NOT be the limiting factor in the speed of your game.

-me

Share this post


Link to post
Share on other sites
vovansim    336
Hi,

Quote:
Original post by fallenang3l
Don't bother, it won't make a difference. Premature optimization is the root of all evil.


What he said. :)

Really, make it so that it makes sense. If the variable has significance only that one function, and really has nothing to do with rest of the class, then put it in the function. If it could be considered a property of the class, then put it in the class.

Then, much later, if your game runs slow, and through the profiler you figre it must be this one function, then you might consider moving the variable. But really, things like this don't matter at all nowadays. It's mostly the algorithms you use that slow you down.

Vovan

Share this post


Link to post
Share on other sites
iMalc    2466
Quote:
Original post by fallenang3l
Don't bother, it won't make a difference. Premature optimization is the root of all evil.

In this case I THOROUGHLY agree! Do not even go there!
Declare it within the smallest scope possible as always.

(we are talking about a built-in type right? no ctor/dtor)

Share this post


Link to post
Share on other sites
Slaru    222
Sounds like I will be creating it on the stack. This variable is only to hold a temporary value for that function and is only needed in the function scope. Thanks

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this