gpt4 book ai didi

Java:在循环中分割或在之前执行哪个更快

转载 作者:行者123 更新时间:2023-12-01 06:33:22 25 4
gpt4 key购买 nike

Goolge 提供了很多比较,但没有针对我正在寻找的内容:

如果我想迭代分割的字符串,什么更好

String[] flagArr = flags.split(";");
for (String f: flagArr) {
// some stuff
}

或者

for (String f: flags.split(";")) {
// some stuff
}

对于第二段代码,我想知道编译器是否足够聪明,只进行一次分割

最佳答案

您可以检查生成的字节码,但我很确定它们都会做同样的事情。为什么第二个会有所不同?

编辑:如您所见,两种方法都只调用 split() 一次。

第一个字节码:

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

public static void main(java.lang.String[]);
Code:
0: ldc #2; //String 1;2;3
2: astore_1
3: aload_1
4: ldc #3; //String ;
6: invokevirtual #4; //Method java/lang/String.split:(Ljava/lang/String;)
[Ljava/lang/String;
9: astore_2
10: aload_2
11: astore_3
12: aload_3
13: arraylength
14: istore 4
16: iconst_0
17: istore 5
19: iload 5
21: iload 4
23: if_icmpge 41
26: aload_3
27: iload 5
29: aaload
30: astore 6
32: aconst_null
33: astore 6
35: iinc 5, 1
38: goto 19
41: return

}

第二个字节码:

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

public static void main(java.lang.String[]);
Code:
0: ldc #2; //String 1;2;3
2: astore_1
3: aload_1
4: ldc #3; //String ;
6: invokevirtual #4; //Method java/lang/String.split:(Ljava/lang/String;)
[Ljava/lang/String;
9: astore_2
10: aload_2
11: arraylength
12: istore_3
13: iconst_0
14: istore 4
16: iload 4
18: iload_3
19: if_icmpge 37
22: aload_2
23: iload 4
25: aaload
26: astore 5
28: aconst_null
29: astore 5
31: iinc 4, 1
34: goto 16
37: return

}

关于Java:在循环中分割或在之前执行哪个更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034257/

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