StringBuilder for Efficient Concatenation
Use StringBuilder to build strings efficiently inside loops and complex formatting.
StringBuilder for Efficient Concatenation
StringBuilder is a mutable alternative to String for building text incrementally. It avoids creating many intermediate String objects.
StringBuilder vs String Concatenation
When concatenating many strings (especially in loops), StringBuilder is dramatically faster because it mutates an internal char buffer rather than creating new objects.
// Inefficient: creates a new String every iteration
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // 1000 new String objects!
}
// Efficient: StringBuilder uses a resizable char buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(',');
}
String efficient = sb.toString(); // one final String createdAll lessons in this course
- String Immutability and the String Pool
- StringBuilder for Efficient Concatenation
- Text Blocks and String.format
- Regular Expressions with Pattern and Matcher