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
开发者_Python百科 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!
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.
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 ...
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.
精彩评论