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 <开发者_StackOverflow社区; 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.
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:
- Redability
- Maintainability
- Understandability
- Clearity
- Testability
- Logically
- Efficiency :-)
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
}
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:
- In the first case, the loop limit will probably be cached in a register
- In the second case, the loop does an extra memory lookup in each iteration. This is because the loop has no guarantee that the size won't change on each iteration, so needs to keep checking the memory value. Technically, there is also the overhead of a function call although a decent JIT compiler is likely to optimise this away completely by inlining.
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 ;-)
If you do the second way itemsList.size()
has to get calculated every time.
And if itemsList
is big, it could take a while
精彩评论