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 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 withinMethod()directly or indirectly in any way.My personal preference, in order to do what I want and write it as I like it, is: