java for each 原理_Java for each实现机制代码原理解析
源測試代碼如下
public class ForEachTest {
public void test4Iterate(Iterable 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 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."":()V
4: return
public void test4Iterate(java.lang.Iterable);
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的性能也會不同
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持易采站長站。
總結
以上是生活随笔為你收集整理的java for each 原理_Java for each实现机制代码原理解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根可达算法的根_好屌好屌的「GC系列」J
- 下一篇: 2021 河南 高考成绩查询,2021河