I am trying to optimize a chunk of code where speed is very important and wondered if checking the int that holds the number of times a for loop is about to loop and not doing the for loop if it is equal to zero was any faster or slower than just letting the for loop execute 0 times.
I realize that any speed improvement would be tiny; it just started to become more of a curiosity. Also would this be different from Java to say C++ or C?
Example:
size=0;
for (int i = 0;i<size;i++)
{
}
or
size=0;
if (size!=0)
{
for (int i = 0;i<size;i++)
{
}
}
Of course, in the real code the size is often not zero, but when it is which would be faster if either?
Academically? Yes, since every time the size isn’t 0, it will run 1 extra comparison.
Realistically? No. When you’re talking comparisons like this, you’re counting nanoseconds, especially after the JVM creates the machine language and it gets executed directly on the processor.
Now, which one should you use. Probably the first one. It doesn’t save time, and it’s shorter and cleaner. Even better, Java has a for-each loop construct that makes it so you don’t have to have the index at all:
For arrays, this compiles to an indexed for-loop. For
Collectionobjects:This one compiles to a for loop with an
Iteratordeclaration.These are the best option if you don’t need the index itself, since it compiles to the same thing after compilation, it’s clear, and it’s the same for both arrays and collections.