Nov 12, 2014

[c++] Cache Member Variables

Reference:

Accessing member variables is a common operation in C++ member functions.

The compiler must often load member variables from memory through the this pointer. Because values are being loaded through a pointer, the compiler sometimes cannot determine when a second load must be performed or whether the value loaded before is still valid. 

In these cases, the compiler must choose the safe, but slow, approach and reload the member variable each time it is accessed. 

You can avoid unnecessary memory reloads by explicitly caching the values of member variables in local variables, as follows: 
  • Declare a local variable and initialize it with the value of the member variable. 
  • Use the local variable in place of the member variable throughout the function. 
  • If the local variable changes, assign the final value of the local variable to the member variable. 
However, this optimization may yield undesired results if the member function calls another member function on that object.

This optimization is most productive when the values can reside in registers, as is the case with primitive types. 

The optimization may also be productive for memory-based values because the reduced aliasing gives the compiler more opportunity to optimize. 

This optimization may be counter productive if the member variable is often passed by reference, either explicitly or implicitly.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.