Search code examples
c++performancepointersmemory-managementdereference

Is there performance to be gained by moving storage allocation local to a member function to its class?


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!


Solution

  • 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 ...