新字符串() 与文本字符串性能
这个问题在StackOverflow上已经问过很多次了,但没有一个是基于性能的。
在《有效的Java》一书中,它给出了
如果在循环或频繁调用的方法中发生,则可以不必要地创建数百万个 String 实例。
String s = new String("stringette");
改进的版本很简单:此版本使用单个 String 实例,而不是每次执行时都创建一个新实例。
String s = "stringette";
因此,我尝试了这两种方法,发现性能有了显著提高:
for (int j = 0; j < 1000; j++) {
String s = new String("hello World");
}
大约需要399 372纳秒。
for (int j = 0; j < 1000; j++) {
String s = "hello World";
}
大约需要23 000纳秒。
为什么会有这么多的性能改进?内部是否有任何编译器优化?