Optimization: Comparisons

The first code optimization technique I’d like to discuss is the use of comparisons. Every modern programming language uses short-circuit boolean evaluation, so there’s not much I can say about that. However when programming there’s a few things you should keep in mind about comparisons. The first and most important being > and < require a lot more work to validate than == or !=. This is important to remember when you are writing high performance routines that require a lot of looping, small details like this can really speed up loops and certainly nested loops. Of course the speed increase won’t be gigantic, but all optimizations that can be applied together should have a nice impact.

You want to loop though an array of numbers. The intuitive way to do this would be to get the length of the array and build a for-loop that will loop while the index is smaller than the length of the array.
for (int i = 0; i < l; i++)
Now lets think about this. We start at 0 so the index will always be smaller or equal the length of the array. We increment the index with 1 on every run, so no indexes are skipped. As i will never be larger than l, we can therefore conclude that we can replace < with !=.
for (int i = 0; i != l; i++)
The same is true for > when you decrementing the index from a certain bigger number.

Another thing to remember is that when writing an if statement, when you know a condition will for example validate as true most of the time, put this is the if-clause.

You have a number to compare, you know that 95% of the time this number will be 5. So you write this:
if (i = 5)

else if (i = 2)


You can check the i = 2 statement first, however as you know the number is usually 5, it will save time to check the i = 5 first as it will usually never have to go any further.

A note: These optimizations are very language specific, for some languages they may not be effective or may even have an adverse effect.

Read More