简体   繁体   中英

Would the compiler optimize this or do I need the assignment?

If I have a method call in a for loop that is the same for all iterations of the loop - is the compiler smart enough to optimize it?

 for (int j = 0; j < 24; j++ ) {
        *destinationPointer++ = identityArray[j] * (1 / powf(2, valueFromAboveInMethod));
 }     

Or should I be explicit and assign it to a value before the loop?

 float value = 1 / powf(2, valueFromAboveInMethod);

 // populate the array
 for (int j = 0; j < 24; j++ ) {
        *destinationPointer++ = identityArray[j] * value;
 }     

I'd be happier if the compiler did something awesome here and I didn't have to use the 4 bytes for the float - this is inside a recursive method.

I personally would use a variable here. Not only because it may provide better code, but also because it shows to anyone reading the code that the value doesn't change [I'd give it a better variable-name than "value", however]. I do expect the compiler to actually pre-calculate the value, but as has been mentioned, it does rely on the compiler understanding that powf is a pure function (has no side-effects and give the same result for the same input every time).

Any additional storage as a consequence of using an extra variable in a recursive call would either be a case of "well, it shouldn't matter" or "you are playing very close to the edge of the abyss of stack overflow". Stack overflow is probably one of the worst types of crashes, as it gives absolutely no warning or way to recover, since the program needs to use a stack to recover, and it may well be the only stack available that overflowed... If your recursive function is either unbounded or you can't guarantee that that the number of recursive calls are well within the limits of the stack, then I would suggest you should redesign this function. Deep recursion is often quite inefficient as well as the fact that it's prone to crashing with stackoverflow [and with a stack that contains forty-thousand calls to the same function, which makes it very easy to figure out why it crashed, but not necessarily easy to figure out the original cause of the deep recursion].

-- Mats

It depends on with what options do you compile it. Usually even with minimal optimization enabled compilers deal with such simple optimizations, however it's better to just do it yourself as you have written in the second code. Anyway if compiler will optimize it, it will keep additional 4 bytes too, because value need to be stored anywhere.

The compiler may not be smart enough to realize powf is stateless.

When in doubt, compile to assembler and check it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM