I have the following situation:
while (node != NULL && has_all_except)
{
...
}
If neither node nor has_all_except are modified in the loop, will gcc optimize the loop to only compute the expression once?
I have studied the Wikipedia article on compiler optimization (http://en.wikipedia.org/wiki/Compiler_optimization) but couldn’t get a definite answer. My guts says it will be optimized.
The
&&operator is lazily evaluated.If
node != NULLis false thenhas_all_exceptwon’t even be considered. This is a language rule, not an optimisation too.Looping unconditionally if neither has been changed is theoretically possible, depending upon where they could have been modified from and how easy it is to spot that. I suspect though that it’s possibly worse for a modern CPU than just applying the tests. (It would introduce more total branches, more code and greater memory requirements – branch prediction on the other hand ought to do well on loop control such as that).
You could implement this kind of “optimisation” yourself using
gototo test this (note: I’m not advocating usinggoto, but it does portably “simulate” the effect of the proposed optimisation under discussion). I think looking at an example makes the problems I discussed clearer e.g.:The problem with this is that we’ve succeed in introducing an unconditional jump, but the unconditional jump itself is conditionally applied and that condition is no simpler than the first part of the
&&itself.Doing this means:
intas the “flag” to see if anything got chagneddo_stuff()andother_stuff()– if anything isn’t cooperative then this isn’t possible (and it’s unlikely your compiler can figure this out for you across trhanslation units)If it’s worth doing and safe to do then I’m fairly confident that it would be done by a suitably modern compiler. If it’s not being done then I suspect it’s not worth it (no better performance), or not safe to apply. Either way the compiler more than likely understands the intricacies of optimising loops for your code on your specific platform far better than the vast majority of programmers!