bread butter
bread butter

Reputation: 617

When and how to use StringBuilder/Buffer efficiently?

I want to create a string which is made by concatenating about 3000 other strings. I hear that using so many strings can be inefficient because they lie in some kind of pool and may not be picked up by the GC immediately after they are not needed.

Is this the best way to go about it -

StringBuilder sb = new StringBuilder("");

for(String s : arrayWith3000Strings)
{
  sb.append(s);
}

or should i concatenate all the strings into one string ?

Upvotes: 1

Views: 1103

Answers (3)

Jiri Kremser
Jiri Kremser

Reputation: 12837

StringBuffer has even better performance than StringBuilder, but StringBuffer is not thread-safe!

EDIT: of course, it is vice versa :)

Upvotes: -1

kosa
kosa

Reputation: 66637

Yes, Your code is good.

Even though you use String concatenation it creates new String objects because Strings are immutable.

Upvotes: 2

paulsm4
paulsm4

Reputation: 121629

This is definitely a case where StringBuilder is preferred.

Strings are "immutable". Any operation that modifies a string (including "append") creates a new string. Using stringbuilder avoids that expense.

This link (one of many) explains further:

Upvotes: 2

Related Questions