Suppose the code blow is my class. It’s simplified and not complete. Let’s focus on the implementation of operator().
class Delta{
public:
long long operator()() {
auto now = steady_clock::now();
auto delta = (now - last).count();
last = now;
return delta;
}
private:
steady_clock::time_point last;
};
operator() may be called thousands of times per second. I just wonder frequently allocate and deallocate variable now and delta may hurt the performance of operator(). So is it better to make now and delta data member of class Delta if I want to maximize the speed? But I also heard that local variable may not even exists when compiled. So somehow the overhead does not exists either.
well, actually the speed of this operator doesn’t make any difference to my Application’s speed. I just wan’t to know a compiler-neutral answer. When this situation comes. Should I make it data members or local variables?
On x86-64, I’d expect this code to end up with both
nowanddeltaallocated in RAX. In assembly language, the code would look something on this order:Of course, in real assembly language, you’d see the mangled names for
steady_clock::now()(for one example), but you get the general idea. Upon entry to any non-static member function, it’s going to havethisin some register. The return value always goes inrax. I don’t see any particularly good reason a compiler would need (or even want) to allocate space for any other variables.On 32-bit x86, there’s a much higher likelihood that this would end up using some stack space, though it’s possible that it would return a 64-bit value in EDX:EAX, in which case things would end up fairly similar to what’s above, just using one more register.
Most other processors start out with more registers than an x86, so the register pressure is lower. On a SPARC, for example, a routine will normally start with 8 local registers free and ready for use, so allocating
nowin a register would be a near certainty.Bottom line: you’re unlikely to see a significant speed difference, but if you do see a difference, I’d guess it’s more likely to favor using a local variable than a member variable.