Is there a performance difference between a for loop and a for-each loop?

前端 未结 16 1265
清歌不尽
清歌不尽 2020-11-22 10:38

What, if any, is the performance difference between the following two loops?

for (Object o: objectArrayList) {
    o.DoSomething();
}

and <

相关标签:
16条回答
  • 2020-11-22 10:53

    The only way to know for sure is to benchmark it, and even that is not as simple as it may sound. The JIT compiler can do very unexpected things to your code.

    0 讨论(0)
  • 2020-11-22 10:57

    Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.

    0 讨论(0)
  • 2020-11-22 10:59

    The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.

    I think the article is now here: new location

    The link shown here was dead.

    0 讨论(0)
  • 2020-11-22 11:00

    By the variable name objectArrayList, I assume that is an instance of java.util.ArrayList. In that case, the performance difference would be unnoticeable.

    On the other hand, if it's an instance of java.util.LinkedList, the second approach will be much slower as the List#get(int) is an O(n) operation.

    So the first approach is always preferred unless the index is needed by the logic in the loop.

    0 讨论(0)
  • 2020-11-22 11:02

    foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.

    Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I think it does E.g. Does it start from zero, does it include or exclude the end point etc.?

    Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.

    0 讨论(0)
  • 2020-11-22 11:02
    public class FirstJavaProgram {
    
        public static void main(String[] args) 
        {
            int a[]={1,2,3,45,6,6};
    
    // Method 1: this is simple way to print array 
    
            for(int i=0;i<a.length;i++) 
            { 
                System.out.print(a[i]+" ");
            }
    
    // Method 2: Enhanced For loop
    
            for(int i:a)
            {
                System.out.print(i+" ");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题