Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point does using a StringBuilder become insignificant or an overhead?

Recently I have found myself using StringBuilder for all string concatenations, big and small, however in a recent performance test I swapped out a colleague's stringOut = string1 + "." string2 style concatenation (being used in a 10000x + loop with the StringBuilder being newed each time) for a StringBuilder just to see what difference it would make in a minor concatenation.

I found, over many runs of the performance test, the change was both insignificantly higher or lower regardless of concatenation or StringBuilder (restating this was for small concatenations).

At what point does the 'newing up' of a StringBuilder object negate the benefits of using one?

like image 731
johnc Avatar asked Feb 15 '09 10:02

johnc


People also ask

On which circumstances is it effective to use StringBuilder?

StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Should you use StringBuilder to construct large text?

Answer. Use StringBuilders exclusively to concatenate many small strings into a large string, or even to concatenate a few large strings. The Text Extension (a System Component starting with 6.0) provides an API for using StringBuilders.

Should you use StringBuilder to construct large text instead of just adding?

If you need to concatenate inside the loop, it is always suggested to use StringBuilder. For simple string concatenation, you need not use StringBuilder , java compiler will do the trick for you. However, if you need to concatenate inside a loop, you need to manually apply StringBuilder.

Is StringBuilder efficient in Java?

Creating and initializing a new object is more expensive than appending a character to an buffer, so that is why string builder is faster, as a general rule, than string concatenation.


1 Answers

The rule that I follow is -

Use a StringBuilder when the number of concatenations is unknown at compile time.

So, in your case each StringBuilder was only appending a few times and then being discarded. That isn't really the same as something like

string s = String.Empty;
for (int i = 0; i < 10000; ++i)
{
    s += "A";
}

Where using a StringBuilder would drastically improve performance because you would otherwise be constantly allocating new memory.

like image 197
Ed S. Avatar answered Sep 17 '22 15:09

Ed S.