Java – for loop efficiency
I'm writing an Android game and trying to be as efficient as possible
I know that for loops are more effective than foreach, but I want to know if there is a difference in the efficiency of the following two projects:
// itemsList is an ArrayList
int length = itemsList.size();
for(int i=0; i < length; i++)
{
// do stuff
}
VS
for(int i=0; i < itemsList.size(); i++)
{
// do stuff
}
resolvent:
It depends. In theory, the first one will be faster because the second one will make function calls in each iteration. In practice, this can be optimized to a large extent. The size may be cached in the object, which will only leave the cost of function calls (actually zero). But if in doubt, please choose the first one. It won't be slow
But in general, remember: premature optimization is the root of all evil
Don't choose specific solutions because you think they may be 100 nanoseconds faster. Instead, write good, reliable and most important readable code. Then, optimize the real bottleneck