Skip to main content
GameDev.net gamedev.net
🔒 Locked

Quick efficiency question

Started by Silex Jan 30, 2004 at 5:01 PM 4 replies 300+ views
Original Post
Silex
Silex
Say I have
class A
{
   calc_dist(const v &cam) { float dist = length( mypos - cam ); };
};

class B
{
   float dist;
   calc_dist(const v &cam) { dist = length( mypos - cam ); };
};

class C
{
   calc_dist(const v &cam) { static float = length( mypos - cam ); };
};
 
and they are called frequently, am I right in assuming B and C tie as far as performance is concerned whereas A sucks?
foofightr
foofightr
A is useless because you are assigning to a temporary variable.
B is the only one that seems to behave correctly.
C does nothing at all after except first time it's called.

I highly doubt this kind of call would be a bottleneck anyway, so don't sweat it. The sqrt() inside of length() is probably taking 10 times longer than the calc_dist() call anyway.

[edited by - foofightr on January 30, 2004 6:09:18 PM]
Silex
Silex
Yeah this is just to satisfy my curiosity. And yeah, the idea behind A is that I'd be using the distance in the same function. And are you sure about C? My impression (naive as it is) was that static variables inside a function meant that the variable was only created once and then all other calls reused it, or something like that [edit: I think this is referred to as 'persistance'].

[edited by - Silex on January 30, 2004 6:18:12 PM]
foofightr
foofightr
Yeah, it''s only created once, which also means it''s only initialized once. It happens that you are calling length() as an initialization...
SiCrane
SiCrane
A static will keep it''s value. However, the way you have things coded now, dist in C::calc_dist() will be initialized only the first time it''s run. If you want it''s value you to change, you''d have to declare the variable in one statement, and do the assignment in another statement. As in:
static float dist;
dist = length( mypos - cam );


As for performance, my bet would be that A would perform slightly better than the other two in the wild (due to spatial locality in the cache).
Silex
Silex
Aha, I see. Thanks guys.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.