Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use StringBuilder?

I understand the benefits of StringBuilder.

But if I want to concatenate 2 strings, then I assume that it is better (faster) to do it without StringBuilder. Is this correct?

At what point (number of strings) does it become better to use StringBuilder?

like image 268
Shiraz Bhaiji Avatar asked Dec 01 '09 12:12

Shiraz Bhaiji


People also ask

When should you use a 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.

When should you use StringBuilder in Java?

StringBuilder is used when we want to modify Java strings in-place. StringBuffer is a thread-safe equivalent similar of StringBuilder . StringBuilder has methods such as append , insert , or replace that allow to modify strings.

When would you use string vs StringBuilder?

When to use which one: If a string is going to remain constant throughout the program, then use String class object because a String object is immutable. If a string can change (example: lots of logic and operations in the construction of the string) then using a StringBuilder is the best option.

Should I use StringBuilder or StringBuffer?

StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer. If you are in a single-threaded environment or don't care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.


1 Answers

I warmly suggest you to read The Sad Tragedy of Micro-Optimization Theater, by Jeff Atwood.

It treats Simple Concatenation vs. StringBuilder vs. other methods.

Now, if you want to see some numbers and graphs, follow the link ;)

like image 127
Alex Bagnolini Avatar answered Sep 28 '22 22:09

Alex Bagnolini