You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public static void main(String[] args) {
String[] arr = new String[]{"he", "llo", "world", "!"};
String s = "";
for(int i = 0; i < arr.length; ++i) {
s = s + arr[i];
}
System.out.println(s);
}
Activity
sweetning0809 commentedon Aug 3, 2024
先随便进行了一点简单的测试,时间确实有很明显落后,可以拿工具再进一步测试时间和内存。
sweetning0809 commentedon Aug 3, 2024
我觉得创建大量临时对象的问题并没有得到解决,只是使用动态创建替换了原来的每一个创建buillder,但是每次创建的的问题并没有得到缓解。

每次依旧是两位的拼接。
sweetning0809 commentedon Aug 3, 2024
补充实验
使用JMH进一步实验,在循环拼接只有2的情况下就有了很明显的落后,更不要说循环次数较多情况(几乎是线性关系的时间增加),所以在循环拼接的时候仍然应该使用string builder。
循环拼接:
Benchmark Mode Cnt Score Error Units
TeststringApplicationTests.testConcatLatinFor thrpt 25 14461326.741 ± 73113.873 ops/s
构造string builder append拼接
Benchmark Mode Cnt Score Error Units
TeststringApplicationTests.testConcatWithSameBuilder thrpt 25 16331234.883 ± 1184275.498 ops/s
Snailclimb commentedon Aug 4, 2024
感谢分享,这样总结会不会更合适一些呢?
在 JDK 9 中,字符串相加“+”改为用动态方法
makeConcatWithConstants()来实现,从而减少了部分临时对象的创建。然而,这种优化主要针对简单的字符串拼接,对于循环中的大量拼接操作,仍然会逐个动态分配内存(类似于两个两个append的概念),并不如手动使用StringBuilder来进行拼接效率高。sweetning0809 commentedon Aug 4, 2024
嗯 对的 我认为是这样的