Jim*_*mmy 13 java string string-concatenation
我一直在阅读我的团队中其他开发人员生成的代码,他们似乎更喜欢使用+=String连接,而我更喜欢使用,.concat()因为它感觉更容易阅读.
我正在尝试准备一个关于为什么使用.concat()更好的论点,我想知道,两者之间的效率有什么不同吗?
我们应该选择哪个选项?
public class Stuff {
public static void main(String[] args) {
String hello = "hello ";
hello += "world";
System.out.println(hello);
String helloConcat = "hello ".concat("world");
System.out.println(helloConcat);
}
}
Run Code Online (Sandbox Code Playgroud)
Buh*_*ndi 10
由于String在java中是不可变的,所以当你执行a时+,+=或者concat(String)生成一个新的String.String越大,所需的时间越长 - 复制的次数越多,产生的垃圾就越多.
今天的java编译器优化了你的字符串连接以使其最佳,例如
System.out.println("x:"+x+" y:"+y);
Run Code Online (Sandbox Code Playgroud)
编译器将其生成为:
System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());
Run Code Online (Sandbox Code Playgroud)
我的建议是编写更易于维护和阅读的代码.
此链接显示StringBuilder与StringBuffer和String.concat的性能 - 完成正确
我同意@darioo和其他大多数答案.始终首先考虑可读性(和可维护性).(对于像这样的简单情况,现代JIT编译器应该没有麻烦.)
但是,这是与您的程序对应的字节码.(注意,在构造字符串时,该+=方法StringBuilder通常是首选方法.)
// String hello = "hello";
0: ldc #2; //String hello
2: astore_1
// hello += "world";
3: new #3; //class java/lang/StringBuilder
6: dup
7: invokespecial #4; //Method StringBuilder."<init>"
10: aload_1
11: invokevirtual #5; //Method StringBuilder.append
14: ldc #6; //String world
16: invokevirtual #5; //Method StringBuilder.append
19: invokevirtual #7; //Method StringBuilder.toString
// System.out.println(hello);
22: astore_1
23: getstatic #8; //Field System.out
26: aload_1
27: invokevirtual #9; //Method PrintStream.println
// String helloConcat = "hello ".concat("world");
30: ldc #2; //String hello
32: ldc #6; //String world
34: invokevirtual #10; //Method String.concat
37: astore_2
// System.out.println(helloConcat);
38: getstatic #8; //Field System.out
41: aload_2
42: invokevirtual #9; //Method PrintStream.println
45: return
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33339 次 |
| 最近记录: |