Copy static member of class to local variable for optimization

When viewing open source code (from OpenCV), I found the following code inside the method:

// copy class member to local variable for optimization int foo = _foo; //where _foo is a class member for (...) //a heavy loop that makes use of foo 

From another question on SO I came to the conclusion that the answer to the question of whether to do this or not , or whether this is done automatically by the compiler, may be dependent on the compiler / installation.

My question is, will it matter if _foo was a member of the static class? Will there still be a problem in this manual optimization, or will access to a static member of a class be more "expensive" than to a local variable?

PS - I ask out of curiosity, and not to solve a specific problem.

+4
source share
4 answers

Access to a resource means deleting a reference to an object in order to access it.

Since the property may change at runtime (reading threads), the compiler will read the value from memory every time the value is available.

Using a local variable will allow the compiler to use case for value, as it can safely assume that the value will not change externally. Thus, the value is read only once from memory.

About your question about the static member, it is the same as it, for example, you can change it with another thread. The compiler will also have to read the value from memory each time.

+6
source

I think that a local variable is more likely to take part in some optimization, precisely because it is local to the function: this fact can be used by the compiler, for example, if it sees that no one is modifying the local variable, then the compiler can load it alone times and use it at each iteration.

In the case of member data, the compiler may have to work harder to conclude that no one is modifying the member. Think of a multi-threaded application and note that the C ++ 11 memory model is multi-threaded, which means that some other thread can change a member, so the compiler cannot conclude that no one is modifying it, so it must emit code for the load element for each expression that uses it, perhaps several times in one iteration, to work with the updated member value.

+4
source

In this example, _foo will be copied to the new local variable. therefore, both cases are the same. Statis values ​​are like any other variable. it is simply stored in another segment of memory intended for static memory.

0
source

Reading a static member of a class is effectively similar to reading a global variable. They both have a fixed address. Reading non-static means first reading this pointer, adding an offset to the result, and then reading this address. In other words, reading non-static requires more steps and access to memory.

-1
source

All Articles