In this post, we compare String concatenation and StringBuilder.
1. String concatenation
Strings are immutable. So we can’t change existing String, every time Java create a new String to replace previous one. String concatenation is adding two strings using operator +;
1 2 3 4 5 6 7 |
String firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName; System.out.println(fullName); |
The result of executing the code above is:
1 2 3 |
John Doe |
2. StringBuilder
StringBuilder is a mutable sequence of characters. When you want to add new string you have to use append() method.
1 2 3 4 5 |
StringBuilder name = new StringBuilder(); name.append(firstName).append(" ").append(lastName); System.out.println(name); |
The result of executing the code above is:
1 2 3 |
John Doe |
3. Compare
String concatenation has the same bytecode as StringBuilder, but if you want to concatenate many times in loops create an instance of StringBuilder every time, and it will be slower than string builder.
1 2 3 4 5 6 |
String fullName = ""; for (int i=0; i<loopAmount; i++){ fullName = fullName + firstName + " " + lastName; } |
1 2 3 4 5 6 |
StringBuilder name = new StringBuilder(); for (int i=0; i<loopAmount; i++) { fullName = (name.append(firstName).append(" ").append(lastName)).toString(); } |
loopAmount | String concatenation | StringBuilder |
1000 | 11 ms | 3 ms |
10000 | 615 ms | 101 ms |
50000 | 8937 ms | 2130 ms |
When using StringBuilder?
You should use StringBuilder when you use
- concatenation in loops
- concatenation using multiple threads
Otherwise, use string concatenation to the code clarity.