Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called?
Assume this method would be called hundreds of times a second…
In case I’m not being clear, here’s some quick examples:
// use local variables class thisClass { public: void callback( msg& msg ) { int varA; double varB; std::string varC; varA = msg.getInt(); varB = msg.getDouble(); varC = msg.getString(); // do a bunch of calculations } }; // use member variables class thisClass { public: void callback( msg& msg ) { m_varA = msg.getInt(); m_varB = msg.getDouble(); m_varC = msg.getString(); // do a bunch of calculations } private: int m_varA; double m_varB; std::string m_varC; };
Executive summary: In virtually all scenarios, it doesn’t matter, but there is a slight advantage for local variables.
Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond.
Warning: In your scenario, performance shouldn’t be the question, but the role of the variables – are they temporary, or state of thisClass?
Warning: First, second and last rule of optimization: measure!
First of all, look at the typical assembly generated for x86 (your platform may vary):
Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn’t hit execution time.
But this means the ecx register isn’t available for other optimizations. However, modern CPUs do some intense trickery to make that less of an issue.
Also, when accessing many objects this may cost you extra. However, this is less than one cycle average, and there are often more opprtunities for pairing instructions.
Memory locality: here’s a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles).
However, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too.
In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance.