4

While browsing open source code (from OpenCV), I came across the following type of code inside a 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've concluded that the answer to whether or not this actually needs to be done or is done automatically by the compiler may be compiler/setting dependent.

My question is if it would make any difference if _foo were a static class member? Would there still be a point in this manual optimization, or is accessing a static class member no more 'expensive' than accessing a local variable?

P.S. - I'm asking out of curiosity, not to solve a specific problem.

4

4 回答 4

6

Accessing a property means de-referencing the object, in order to access it.

As the property may change during the execution (read threads), the compiler will read the value from memory each time the value is accessed.

Using a local variable will allow the compiler to use a register for the value, as it can safely assume the value won't change from the outside. This way, the value is read only once from memory.

About your question concerning the static member, it's the same, as it can also be changed by another thread, for instance. The compiler will also need to read the value each time from memory.

于 2013-01-20T12:39:26.677 回答
4

I think a local variable is more likely to participate 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 nobody modifies the local variable, then the compiler may load it once, and use it in every iteration.

In case of member data, the compiler may have to work more to conclude that nobody modifies the member. Think about multi-threaded application, and note that the memory model in C++11 is multi-threaded, which means some other thread might modify the member, so the compiler may not conclude that nobody modifies it, in consequence it has to emit code for load member for every expression which uses it, possibly multiple times in a single iteration, in order to work with the updated value of the member.

于 2013-01-20T12:39:59.163 回答
0

In this example the the _foo will be copied into new local variable. so both cases the same. Statis values are like any other variable. its just stored in different memory segment dedicated for static memory.

于 2013-01-20T13:47:22.357 回答
-1

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

于 2013-01-20T15:10:36.563 回答