c++ – Should I avoid repeated access to the same method inside a loop?

Question:

I care about the final performance of an executable, at the same time, I don't want to penalize the programmer with excessive or unnecessary care in the code.

In the code below, for example, it will return the same value as the getPosition method for 10000 times:

for (int i=0; i<10000 ; i++)
    std::cout << i + window.getPosition().x << endl;

In this specific case, I know that window.getPosition().x will always return the same value .

To avoid a performance loss, should I change the code to, for example:

const int x = window.getPosition().x;
for (int i=0; i<10000 ; i++)
    std::cout << i + x << endl;

This always involves an additional concern for the programmer.

Or is there some smart cache where I shouldn't worry about it?

Answer:

It is possible that it has some optimization in code that is guaranteed not to change. It's not the case. So it might be better to do it outside. You know it returns the same value, the compiler doesn't. I'm assuming that it doesn't return a constant and doesn't do practically anything else, because then it could be that the method can be optimized to keep the expression in place of the call and as the expression is known as a constant already in the compilation and then you don't even have to do it the segregation. In fact it is possible that even the tie will disappear. Of course it depends on the compiler and how the method was written.

Optimizations always depend on several factors, such as the compiler you are using, the platform that will be generated, the compiler version, the settings used, the context.

If the method has side effects that will potentially yield different results with each call, then caching a result before the loop can prevent it from catching the changes. On the other hand, you may not want to get changes, so putting them inside may not produce the expected result. So where to put it has to do with the desired semantics rather than optimization.

Note that it's not just a matter of the result returned. If it always gives the same result, but do something collateral in the method call once or 10000 times will give different total result, even if the returned result is different.

Programmer exists to have these concerns. At least the most professional ones. For the most amateurs it may matter little. The trend is for artificial intelligence to solve simple cases in the very long term, and these programmers should be out of work.

Scroll to Top