Is there a performance difference between a for lo

2018-12-31 16:45发布

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

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

and

for (int i=0; i<objectArrayList.size(); i++) {
    objectArrayList.get(i).DoSomething();
}

16条回答
不流泪的眼
2楼-- · 2018-12-31 16:56

Here is a brief analysis of the difference put out by the Android development team:

https://www.youtube.com/watch?v=MZOf3pOAM6A

The result is that there is a difference, and in very restrained environments with very large lists it could be a noticeable difference. In their testing, the for each loop took twice as long. However, their testing was over an arraylist of 400,000 integers. The actual difference per element in the array was 6 microseconds. I haven't tested and they didn't say, but I would expect the difference to be slightly larger using objects rather than primitives, but even still unless you are building library code where you have no idea the scale of what you will be asked to iterate over, I think the difference is not worth stressing about.

查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 16:56
1. for(Object o: objectArrayList){
    o.DoSomthing();
}
and

2. for(int i=0; i<objectArrayList.size(); i++){
    objectArrayList.get(i).DoSomthing();
}

Both does the same but for easy and safe programming use for-each, there are possibilities for error prone in 2nd way of using.

查看更多
唯独是你
4楼-- · 2018-12-31 16:59

Well, performance impact is mostly insignificant, but isn't zero. If you look at JavaDoc of RandomAccess interface:

As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:

for (int i=0, n=list.size(); i < n; i++)
    list.get(i);

runs faster than this loop:

for (Iterator i=list.iterator(); i.hasNext();)
      i.next();

And for-each loop is using version with iterator, so for ArrayList for example, for-each loop isn't fastest.

查看更多
旧时光的记忆
5楼-- · 2018-12-31 17:00

It's weird that no one has mentioned the obvious - foreach allocates memory (in the form of an iterator), whereas a normal for loop does not allocate any memory. For games on Android, this is a problem, because it means that the garbage collector will run periodically. In a game you don't want the garbage collector to run... EVER. So don't use foreach loops in your draw (or render) method.

查看更多
情到深处是孤独
6楼-- · 2018-12-31 17:02

All these loops do the exact same, I just want to show these before throwing in my two cents.

First, the classic way of looping through List:

for(int i=0;i<strings.size();i++) { /* do something using strings.get(i) */ }

Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).

for(String s : strings) { /* do something using s */ }

Third, the micro-optimized for loop:

int size = strings.size();
for(int i=0;++i<=size;) { /* do something using strings.get(i) */ }

Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.

While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java for-each loop (some refer to it as Iterator loop and others as for-in loop) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.

If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.

查看更多
素衣白纱
7楼-- · 2018-12-31 17:03

There appears to be a difference unfortunately.

If you look at the generated bytes code for both kinds of loops, they are different.

Here is an example from the Log4j source code.

In /log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java we have a static inner class called Log4jMarker which defines:

    /*
     * Called from add while synchronized.
     */
    private static boolean contains(final Marker parent, final Marker... localParents) {
        //noinspection ForLoopReplaceableByForEach
        for (final Marker marker : localParents) {
            if (marker == parent) {
                return true;
            }
        }
        return false;
    }

With standard loop:

  private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);
    Code:
       0: iconst_0
       1: istore_2
       2: aload_1
       3: arraylength
       4: istore_3
       5: iload_2
       6: iload_3
       7: if_icmpge     29
      10: aload_1
      11: iload_2
      12: aaload
      13: astore        4
      15: aload         4
      17: aload_0
      18: if_acmpne     23
      21: iconst_1
      22: ireturn
      23: iinc          2, 1
      26: goto          5
      29: iconst_0
      30: ireturn

With for-each:

  private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);
    Code:
       0: aload_1
       1: astore_2
       2: aload_2
       3: arraylength
       4: istore_3
       5: iconst_0
       6: istore        4
       8: iload         4
      10: iload_3
      11: if_icmpge     34
      14: aload_2
      15: iload         4
      17: aaload
      18: astore        5
      20: aload         5
      22: aload_0
      23: if_acmpne     28
      26: iconst_1
      27: ireturn
      28: iinc          4, 1
      31: goto          8
      34: iconst_0
      35: ireturn

What is up with THAT Oracle?

I've tried this with Java 7 and 8 on Windows 7.

查看更多
登录 后发表回答