Class member or stack variable

Started by
4 comments, last by Slaru 19 years, 9 months ago
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
Advertisement
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
Don't bother, it won't make a difference. Premature optimization is the root of all evil.
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
Vovan
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)
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
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

This topic is closed to new replies.

Advertisement