Reputation: 255
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
}
Upvotes: 3
Views: 184
Reputation: 421340
To limit the scope of the throw-away variable, and still call size()
just once, you can write
for(int i=0, n = itemsList.size(); i < n; i++) {
// do stuff
}
When choosing between two alternatives, prioritize them in the following order:
Upvotes: 4
Reputation: 106401
The first is more efficient, although only very marginally given a good compiler.
It won't make any noticeable difference unless you are doing the loop literally millions of times per second.
The reason:
Upvotes: 1
Reputation: 3080
if you use the list only for read then you should use this
int length = itemsList.size();
for(int i=0; i < length; i++)
{
// do stuff
}
but if you remove elements from the list then use this approach
for(int i=0; i < itemsList.size(); i++)
{
// do stuff
}
Upvotes: 2
Reputation: 116200
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.
Upvotes: 11
Reputation: 2616
if you use
for(int i=0; i < itemsList.size(); i++)
{
// do stuff
}
You will always call the itemsList.size()-method. So, if you store this value in a variable, you will be faster. And try to use final variables ;-)
Upvotes: 0
Reputation: 146360
If you do the second way itemsList.size()
has to get calculated every time.
And if itemsList
is big, it could take a while
Upvotes: -1