Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using += for strings in a loop, is it bad practice?

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"

Why is this so?

like image 992
andrew Avatar asked Sep 01 '13 18:09

andrew


1 Answers

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

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.

So when you do this:

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

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.

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.

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.

like image 135
Dhruv Kapoor Avatar answered Sep 20 '22 13:09

Dhruv Kapoor