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

前端 未结 16 1523
清歌不尽
清歌不尽 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 11:16

    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.

提交回复
热议问题