3 ms·
If the compiler knows that the loop will terminate in 'x' iterations, it can do things like hoist some arithmetic out of the loop. The simplest example would be
by joosters 7y ago
If the compiler knows that the loop will terminate in 'x' iterations, it can do things like hoist some arithmetic out of the loop. The simplest example would be if the code inside the loop contained a line like 'counter++'. Instead of executing 'x' ADD instructions, the binary can just do one 'counter += x' add at the end.
- iainmerrick 7y agoWhat I’m driving at is, if the loop really doesn’t terminate, it would still be safe to do that optimization because the incorrectly-optimized code would never be executed. I guess that doesn’t necessarily help in the “+=2” case, where you probably want the optimizer to do a “result += x/2”. In general, I’d greatly prefer to work with a compiler that detected the potential infinite loop and flagged it as an error.