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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With