CoMPMStR wrote:Well the only thing I can think of that can be any faster is using a prefix operation.
- Code: Select all
for ( int I = iTotal; --I >= 0; ) {
// Do something.
}
Correct.
If we can not assume we are allowed to modify iTotal then we use a standard iterator from iTotal down to 0.
If we can modify iTotal, it would be better to use iTotal directly in place of I as has been suggested earlier.
Either way, the structure of the loop changes slightly to accommodate the new ability we have to check against being below 0.
The basic rule of optimization that all children learn in preschool is that prefix is never slower than and sometimes faster than postfix. We want to use it when possible, but our previous loops were forced into postfix simply because of the unsigned nature of being unable to compare below 0.
Postfix still provides the best performance of any alternative in those cases, but simply by changing the sign we gain access to the best possible case, which generates the smallest and fastest code you can get.
If you are a Java coder, this is going to be by far your loop of choice. Java has no unsigned type, so all of your loops will be signed. This loop is especially fast and small in Java, so it is an absolute must for Java programmers.
Who knew that basic loops could be so challenging/involved? Look under every rock and question everything. Just because it is exceptionally common does not mean it is correct or could not be improved.
CoMPMStR wrote:Couldn't this be used as well?
- Code: Select all
for ( int I = -1; ++I < iTotal; ) {
// Do something.
}
Prefix increment is not the only optimization making the loop into its 100% form. Checking against 0 helps greatly, as there are a million ways for the compiler to do it and all are faster and smaller than loading a variable into memory and checking against it.
If you have to go from 0 to iTotal (because the loop internals require it etc.) then the most common form is better than this. This loop adds an additional increment operation over the traditional loop, and the traditional loop can still use ++I. It is also difficult to understand when people have to go over your code in the future, but then again many of these optimizations result in less-common code. Just not as uncommon as this.
L. Spiro
P. S.: For some reason the 100% form of the unsigned loop does not work in L. Spiro Script. It skips index 0.
I will investigate and fix later but be warned that you can not use the unsigned form yet.
You can, however, use the signed form.