views:

67

answers:

3

Suppose I have the following C++ class:

class Foo
{
  double bar(double sth);
};

double Foo::bar(double sth)
{
  double a,b,c,d,e,f
  a = b = c = d = e = f = 0;
  /* do stuff with a..f and sth */
}

The function bar() will be called millions of times in a loop. Obviously, each time it's called, the variables a..f have to be allocated. Will I gain any performance by making the variables a..f members of the Foo class and just initializing them at the function's point of entry? On the other hand, the values of a..f will be dereferenced through this->, so I'm wondering if it isn't actually a possible performance degradation. Is there any overhead to accessing a value through a pointer? Thanks!

+6  A: 

On all architectures I know allocation/deallocation of built-ins is done by manipulating the stack register. I suppose that this takes almost no time at all compared to the rest of the function.

If you feel that incrementing/decrementing a value in a processor register might help, you're down to micro-optimizations. They should be done as the last thing before shipping and (as all optimizations) they should be guided by measuring, not by guessing.

sbi
+3  A: 

If the variables really are local to the function and are used nowhere else, then they should be local to the function. I can't see how making them members will increase performance. You should however use initialisation rather than assignment:

double a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;

This may or may not be significant for doubles, but certainly will be for user-defined types such as strings.

anon
+1, but IIRC it should be 0.0 (double), not 0 (integer). The compiler should be smart enough not to perform the cast at runtime, but you never know... :)
Matteo Italia
@Mtteo I do know - no cast will be performed t runtime - the compiler will emit the correct code at compile time.
anon
+2  A: 

Access to stack-allocated variables is faster than to class members. Stack variables are dereferenced using stack pointer, without using of a class pointer. Add new class members only if it is required by program algorithm. Initialize stack variables directly in declaration:

double a = 0.0, b = 0.0 ...

Alex Farber