, is this a viable way to make your code faster?
如果您的,您甚至可以使其更快String s;
是一个非静态场。当您进行以下操作时,静态字段比非静态字段慢referencing
它十亿次
public static void main(String[] args) {
startTime = System.nanoTime();
String s = "";
.
.
}
EDIT:
为什么速度更快??
这是由于字符串引用了静态字段。
你可以在它的字节码中看到它
0: ldc #23 // String
2: putstatic #25 // Field s:Ljava/lang/String;
5: iconst_0
6: istore_1
7: goto 22
10: getstatic #25 // Field s:Ljava/lang/String;
13: ldc #23 // String
15: invokevirtual #27 // Method java/lang/String.equals:(L
java/lang/Object;)Z
18: pop
19: iinc 1, 1
22: iload_1
23: ldc #33 // int 1000000000
25: if_icmplt 10
28: return
如你看到的getStatic
and putStatic
将被调用十亿次,它的作用是调用静态字段的引用并使用 putStatic 放置字符串的引用
获取静态- 获取一个类的静态字段值,该字段通过常量池索引中的字段引用来标识(index1
放置静态- 将静态字段设置为类中的值,其中该字段由常量池中的字段引用索引标识(indexbyte1
看看那些位移位这就是程序缓慢的原因
另外,如果您使用的是global/member field
它将创建相同的bytecode但它会使用getfield
and putfield
与 static 相同getStatic
and putStatic
现在让我们看看non static field
字节码
0: ldc #21 // String
2: astore_1
3: iconst_0
4: istore_2
5: goto 23
8: aload_1
9: ldc #21 // String
11: invokevirtual #23 // Method java/lang/String.equals:(L
java/lang/Object;)Z
14: ifeq 20
17: ldc #21 // String
19: astore_1
20: iinc 2, 1
23: iload_2
24: ldc #29 // int 1000000000
26: if_icmplt 8
29: return
正如你所看到的,它只使用astore_1
and aload_1
无需额外操作即可保存和加载非静态字段的引用。