I am writing an Android game and trying to be as efficient as possible.
I know that a for loop is more efficient than a foreach, but I was wondering if there was a difference in efficiency in the following 2 items:
// 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
}
It depends. Thoretically the first will be faster, because the second will have to do a function call in each iteration. In practise this may be optimized to a great degree. The size will probably be cached in the object, which leaves you with only the overhead of a function call (which is virtually nil).
But when in doubt, choose the first. It will not be slower.
But in general, remember: premature optimization is the root of all evil.
Don’t choose specific solutions because you think they may be a nanosecond faster. Instead, write good, solid and above all readable code. Then, optimize the real bottlenecks.