To view parent comment, click here.
To read all comments associated with this story, please click here.
My example was to show that it's easy for the optimizer to get rid of range checks. The code shown was how naive range-checks would be inserted, before optimization.
In any case, using an iterator in a tight loop is a bad idea. The iterator version would expand into something like:
double* ptr = vec;
double sum = 0.0;
while(ptr != vec.end) {
double t0 = *ptr;
if(ptr != vec.end) ++ptr; // will be eliminated
sum += (t0 * t0);
}
The range-check can be eliminated because the condition protecting it is made redundent by the loop-end test. This is exactly the same reason the range-check can be eliminated in the other example I showed.
However, this example is worse because it replaces array accesses with pointer arithmetic. The compiler will eventually lower the array accesses to pointer arithmetic anyway, but late in the optimizer. Before that, keeping things in array form makes classical loop/array optimizations (eg: dependence analysis) much easier.






Member since:
2005-07-06
rayiner,
your example in C++ would be best implemented with an iterator or with the foreach macro described earlier. All your example proves is that when there's no link between syntax and semantics the compiler cannot optimize unnecessary code away, therefore the solution is to create that link, which is what an interator pattern does.