开发者

Will the class method call be optimized out in the for loop?

开发者 https://www.devze.com 2023-04-11 13:37 出处:网络
code for (size_t i = 0; i < myClassObject.Method(); ++i) some work; I am wondering if the compiler will optimize out the method call and turn it into this?

code

for (size_t i = 0; i < myClassObject.Method(); ++i)
  some work;

I am wondering if the compiler will optimize out the method call and turn it into this?

size_t result = myClassObject.Method();
for (size_t i = 0; i < result; ++i
  some work;

Would it matter 开发者_JAVA百科if it was a function call instead? My worry is that I could be doing 1000's of unneeded calls to the method, but I prefer to write it with the method call in the condition.


You should state in code what you want to do. If you need a sum, you wouldn't write code that multiplies instead of adding just because you prefer to do so. It needs a smart compiler to realize that the call to Method() has no side effects, and that the loop of the body does not modify the parameters used within Method() directly or indirectly in any way.

My personal preference, in order to do what I want and write it as I like it, is:

for (size_t i = 0, result = myClassObject.Method(); i < result; ++i )
   some work;


It depends on whether the compiler can prove that the result of the call cannot possibly change in the loop body, so don't rely on it. If you want to do the hoisting explicitly, the standard way to write it is like this:

for (std::size_t i = 0, end = myClassObject.Method(); i != end; ++i)
{
  // ...
}

The same applies to iterator-based loops.


As a rule this would be an incorrect optimization, as the method may not return the same result on every call. Consider if it returned the current time.

If the method definition is available in the same compilation unit (in an included header file or the same source file) and it's simple enough for the compiler to tell it always returns the same result, then you may get this optimization. I think this is especially likely if the method is declared inline.

I believe gcc at least now has inter-module optimization with some compile flags, that may also do it across source file boundaries. No idea about other compilers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号