首页 > 编程语言 > Java for each实现机制代码原理解析
2020
10-08

Java for each实现机制代码原理解析

源测试代码如下

public class ForEachTest {
  public void test4Iterate(Iterable<String> strings) {
    for (String str : strings) {
      System.out.println(str);
    }
  }

  public void test4Array(String[] strings) {
    for (String str : strings) {
      System.out.println(str);
    }
  }
}

执行编译命令

javac ForEachTest.java

使用idea查看反编的Java文件

import java.util.Iterator;
public class ForEachTest {
  public ForEachTest() {
  }
  public void test4Iterate(Iterable<String> var1) {
    Iterator var2 = var1.iterator();
    while(var2.hasNext()) {
      String var3 = (String)var2.next();
      System.out.println(var3);
    }

  }
  public void test4Array(String[] var1) {
    String[] var2 = var1;
    int var3 = var1.length;

    for(int var4 = 0; var4 < var3; ++var4) {
      String var5 = var2[var4];
      System.out.println(var5);
    }
  }
}

执行指令查看对应的汇编指令

javap -c ForEachTest.class

Compiled from "ForEachTest.java"
public class ForEachTest {
 public ForEachTest();
  Code:
    0: aload_0
    1: invokespecial #1         // Method java/lang/Object."<init>":()V
    4: return

 public void test4Iterate(java.lang.Iterable<java.lang.String>);
  Code:
    0: aload_1
    1: invokeinterface #2, 1      // InterfaceMethod java/lang/Iterable.iterator:()Ljava/util/Iterator;
    6: astore_2
    7: aload_2
    8: invokeinterface #3, 1      // InterfaceMethod java/util/Iterator.hasNext:()Z
   13: ifeq     36
   16: aload_2
   17: invokeinterface #4, 1      // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
   22: checkcast   #5         // class java/lang/String
   25: astore_3
   26: getstatic   #6         // Field java/lang/System.out:Ljava/io/PrintStream;
   29: aload_3
   30: invokevirtual #7         // Method java/io/PrintStream.println:(Ljava/lang/String;)V
   33: goto     7
   36: return

 public void test4Array(java.lang.String[]);
  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: getstatic   #6         // Field java/lang/System.out:Ljava/io/PrintStream;
   23: aload     5
   25: invokevirtual #7         // Method java/io/PrintStream.println:(Ljava/lang/String;)V
   28: iinc     4, 1
   31: goto     8
   34: return
}

由反编类和汇编指令可以看到对于Iterable类,是通过其迭代方法执行for each,而对于数组是通过传统的for循环方式执行迭代

因为集合类的for each是基于迭代器循环的,所以根据迭代器实现的不同,for each的性能也会不同

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧