Below is what I’ve found to be the most consistant performance boost with miminal optimization effort on a micro level. Other people are encouraged to post their pet optimizations.
bStructure boolean experssions to evaluate against zero.[/b]
Java, and many other languages/cpus, has special opt codes to test if something is equal to zero as opposed to the generic opt codes to test if a == b. I find this most useful with for loops.
For example:
int a[] = new int[1000000];
for (int i = 0; i < a.length; i++) {
// Do stuff
}
is slower than:
int a[] = new int[1000000];
for (int i = a.length-1; i >= 0; i--) {
// EDITED: Thanks to kenrod for noticing a bug, see his post below for details
// Do stuff
}
There is actually another optimization in the above example. The lookup of the length of a is only done once in the second example which also improves the speed, probably more than the test against zero optimization does.
For the record, I consider the follower to be even more optimized but I’ve found it makes the code harder to read so I never use it.
int a[] = new int[1000000];
for (int i = a.length; --i >= 0;) {
// Do stuff
}
This saves one fetch from memory because the decrement is done with the same fetch of i that is used in the boolean expression instead of being different steps for the decrement and then the test.
Hope this is useful and if I’m wrong please correct me.