英文:
Why is it not recommended to change strings in a loop? What is recommended to use?
问题
为什么不建议在循环中修改字符串?推荐使用什么方法?
英文:
a question from the Java interview preparation that I didn't find an answer to
Why is it not recommended to change strings in a loop? What is recommended to use?
答案1
得分: 2
字符串是不可变对象,因此在向字符串追加内容时,编译器可能需要创建至少一个新对象来保存结果。在循环中构造字符串需要在每次迭代中都创建一个新的字符串,从而消耗更多的时间和内存。这将严重影响算法的性能。
这里提供了使用StringBuffer或StringBuilder来更新字符串的解决方案。
r = new Random(120);
StringBuilder sb = new StringBuilder();
for(int i=0; i<100; i++) {
sb.append(r.nextInt(2));
}
s = sb.toString();
英文:
Strings are immutable objects and therefore possibly the compiler has to create at least one new object to hold the result when appending to strings. Constructing a string in a loop requires creating a new string in every iteration and therefore consuming more time and memory. This will affect the performance of the algorithm badly.
This provides a solution to update strings using StringBuffer or StringBuilder.
r = new Random(120);
StringBuilder sb = new StringBuilder();
for(int i=0; i<100; i++) {
sb.append(r.nextInt(2));
}
s = sb.toString();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论