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

网友投稿 279 2022-12-03


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

源测试代码如下

public class ForEachTest {

publhttp://ic 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的性能也会不同


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:浅谈SpringBoot2.3 新特配置文件属性跟踪
下一篇:Springboot hibernate envers使用过程详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~