为什么不推荐在循环中更改字符串?推荐使用什么?

huangapple go评论74阅读模式
英文:

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&lt;100; i++) {
    sb.append(r.nextInt(2));
}
s = sb.toString();

huangapple
  • 本文由 发表于 2020年7月25日 18:06:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63087041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定