gpt4 book ai didi

java - 比较一个简单循环的 java 字节码?

转载 作者:行者123 更新时间:2023-11-29 07:16:37 28 4
gpt4 key购买 nike

我试图找出这两个循环在编译时的相似程度:

for (int i = 0; i < result.length; i++){
result[i] = array[((i < index) ? i : i + 1)];
}

for (int i = 0; i < result.length; i++){
if(i < index) result[i] = array[i];
else result[i] = array[i + 1];
}

我发现很难找出每个循环的操作位置。
我应该如何比较这两个循环?谢谢

这是我使用 javap -c 运行程序时得到的结果:

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

public static void main(java.lang.String[]);
Code:
0: new #2 // class Test
3: dup
4: invokespecial #3 // Method "<init>":()V
7: pop
8: return

public void Test();
Code:
0: bipush 10
2: newarray int
4: astore_1
5: iconst_0
6: istore_2
7: iload_2
8: bipush 10
10: if_icmpge 23
13: aload_1
14: iload_2
15: iload_2
16: iastore
17: iinc 2, 1
20: goto 7
23: aload_0
24: aload_1
25: iconst_5
26: invokespecial #4 // Method removeAndTrimConcise:([II)[I
29: pop
30: bipush 10
32: newarray int
34: astore_1
35: iconst_0
36: istore_2
37: iload_2
38: bipush 10
40: if_icmpge 53
43: aload_1
44: iload_2
45: iload_2
46: iastore
47: iinc 2, 1
50: goto 37
53: aload_0
54: aload_1
55: iconst_5
56: invokespecial #5 // Method removeAndTrim:([II)[I
59: pop
60: return
}

最佳答案

应该大致介于 newarray(我假设您在每个循环之前创建一个新数组)和 goto(如您所见,将控制流带回到上一行,因此循环):

第一个循环:

   2: newarray       int
4: astore_1
5: iconst_0
6: istore_2
7: iload_2
8: bipush 10
10: if_icmpge 23
13: aload_1
14: iload_2
15: iload_2
16: iastore
17: iinc 2, 1
20: goto 7

第二个:

  32: newarray       int
34: astore_1
35: iconst_0
36: istore_2
37: iload_2
38: bipush 10
40: if_icmpge 53
43: aload_1
44: iload_2
45: iload_2
46: iastore
47: iinc 2, 1
50: goto 37

它们看起来非常相似。

关于java - 比较一个简单循环的 java 字节码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016450/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com