在循环中为字符串使用+ =,这是不好的做法吗? [英] Using += for strings in a loop, is it bad practice?

查看:61
本文介绍了在循环中为字符串使用+ =,这是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一篇文章中看到了这种字符串构建方法,此方法已被删除.

I saw this method of string building used in another post which has since been removed.

其中一条评论将这种做法描述为职业限制"

One of the comments described the practice as "career limiting"

为什么会这样?

推荐答案

如果您在这里谈论Java,我会回答.

I'll answer assuming you're talking of Java here.

我可以想到不止一个原因.首先是Java字符串是不可变的,当您执行+=连接字符串时,将创建一个新的String对象,并将对该对象的引用分配给您的字符串变量.

I can think of more than one reason. The first is that Java strings are immutable, and when you do a += to concatenate strings, a new String object is created, and the reference to that is assigned to your string variable.

因此,当您这样做时:

for (int i = 0; i < 100; i++)
    myString += ...blah...

您正在创建100个新的字符串对象.请注意,旧的确实会随处可见,因此,由于我们没有存储对它们的引用,因此它们最终将在一段时间内被垃圾回收.但是,这仍然不好,因为垃圾回收需要时间,并且堆中的对象过多会降低应用程序的速度.此外,如果您不打算使用它们,为什么还要创建这么多对象.

You're creating a 100 new string objects. Note that the old ones are really going anywhere, so they'll just end up being garbage collected in a while, since we're not storing references to them. This is still not good, though, since garbage collection takes time and having too many objects in your heap can slow down your application. Besides, why create so many objects if you don't intend to use them.

当然,更好的解决方案是使用StringBuilder

A better solution is to use StringBuilder, of course;

StringBuilder myString = new StringBuilder();
for (int i = 0; i < 100; i++)
    myString.append(...blah...);
String s = myString.toString();

另一个原因可能是,如果您已经知道需要追加哪些字符串(或至少是总大小的估计值),则可以预分配空间,以便新空间不会当您的字符串变大时,不需要时不时地进行分配.

Another reason could be that if you already have an idea of what strings you need to append (or at least an estimate of the total size), you could preallocate space, so that new space doesn't need to be allocated every now and then as your string gets bigger.

最后,您可以使用char数组,预分配空间,并使用这个有趣的观点甚至可以做得更好是Joel Spolsky关于C的标准库字符串连接功能的.

Finally, you could use an array of char's, preallocate space, and do even better using this interesting point that Joel Spolsky made about C's standard library string concatenation functionality.

这篇关于在循环中为字符串使用+ =,这是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆