更新时间:2023-11-29 16:09:22
由于字符串在Java中是不可变的,因此在执行 +
, + =
或concat(String)
,将生成一个新的String.字符串越大,花费的时间越长-要复制的内容更多,并且会产生更多的垃圾.
Since String is immutable in java, when you do a +
, +=
or concat(String)
, a new String is generated. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced.
例如,当今的Java编译器会优化您的字符串连接以使其达到***状态,例如
Today's java compilers optimizes your string concatenation to make it optimal, e.g.
System.out.println("x:"+x+" y:"+y);
编译器将其生成为:
System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());
我的建议是编写易于维护和阅读的代码.
My advice is to write code that's easier to maintain and read.