String vs StringBuilder in Java - Performance Comparison
We want to see how fast string operations run when using String and StringBuilder.
How does the time to build or change a string grow as the string gets longer?
Analyze the time complexity of the following code snippet.
String result = "";
for (int i = 0; i < n; i++) {
result += i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(i);
}
String finalResult = sb.toString();
This code builds a string by adding numbers from 0 to n-1 using two ways: String concatenation and StringBuilder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a number to the string inside a loop.
- How many times: The loop runs n times, repeating the add operation each time.
When using String concatenation, each add creates a new string copying old content, so work grows quickly.
| Input Size (n) | Approx. Operations (String) | Approx. Operations (StringBuilder) |
|---|---|---|
| 10 | About 55 copies | About 10 appends |
| 100 | About 5,050 copies | About 100 appends |
| 1000 | About 500,500 copies | About 1000 appends |
Pattern observation: String concatenation work grows much faster than StringBuilder as n grows.
Time Complexity: O(n^2) for String concatenation, O(n) for StringBuilder
Using String concatenation takes much more time as the string grows, but StringBuilder stays fast and grows evenly.
[X] Wrong: "Using + to add strings in a loop is always fast enough for any size."
[OK] Correct: Each + creates a new string copying all old content, so time grows very fast and slows down big loops.
Knowing when to use StringBuilder shows you understand how code speed changes with input size, a key skill in programming.
"What if we used StringBuffer instead of StringBuilder? How would the time complexity change?"
Practice
StringBuilder instead of String in Java?Solution
Step 1: Understand the nature of
StringandStringBuilderStringobjects are immutable, meaning they cannot be changed once created. Changing text creates new objects, which is slow and uses more memory.Step 2: Identify when
StringBuilderis betterStringBuilderallows changing text without creating new objects, making it efficient for many modifications.Final Answer:
UseStringBuilderwhen you need to change text many times efficiently. -> Option AQuick Check:
Many changes =StringBuilder[OK]
- Thinking String is better for many changes
- Confusing immutability of String
- Assuming StringBuilder uses more memory always
StringBuilder object with initial text "Hello"?Solution
Step 1: Recall the correct constructor syntax for StringBuilder
TheStringBuilderclass requires thenewkeyword and parentheses with the initial string inside.Step 2: Check each option for syntax correctness
StringBuilder sb = new StringBuilder("Hello"); usesnew StringBuilder("Hello"), which is correct. Options A, B, and D have syntax errors or wrong usage.Final Answer:
StringBuilder sb = new StringBuilder("Hello"); -> Option DQuick Check:
Use new + constructor for StringBuilder [OK]
- Omitting 'new' keyword
- Using assignment without constructor
- Using array syntax mistakenly
StringBuilder sb = new StringBuilder("Hi");
sb.append("!");
sb.append(" How are you?");
System.out.println(sb.toString());Solution
Step 1: Understand what append() does on StringBuilder
Eachappend()adds the given text to the end of the current StringBuilder content without spaces unless explicitly added.Step 2: Trace the code execution
Initial text is "Hi". First append adds "!" making "Hi!". Second append adds " How are you?" (with leading space), resulting in "Hi! How are you?".Final Answer:
Hi! How are you? -> Option CQuick Check:
Appends add text exactly as given [OK]
- Ignoring spaces in appended strings
- Assuming append replaces text
- Printing StringBuilder object directly without toString()
StringBuilder sb = new StringBuilder("Test");
sb = sb + "ing";
System.out.println(sb);Solution
Step 1: Check the use of + operator with StringBuilder
The + operator cannot be used to add a String to a StringBuilder object directly. This causes a compile-time error.Step 2: Understand correct way to append text to StringBuilder
Usesb.append("ing")to add text instead of + operator.Final Answer:
Cannot use + operator to concatenate StringBuilder and String. -> Option AQuick Check:
Use append(), not +, with StringBuilder [OK]
- Trying to use + with StringBuilder
- Thinking println can't print StringBuilder
- Forgetting semicolons
Option A:
String sentence = "";
for (String word : words) {
sentence += word + " ";
}
Option B:
StringBuilder sentence = new StringBuilder();
for (String word : words) {
sentence.append(word).append(" ");
}Solution
Step 1: Analyze Option B is better because String is simpler to use. (String concatenation in loop)
Each concatenation with += creates a new String object because Strings are immutable, causing slow performance and more memory use.Step 2: Analyze Option B is better because StringBuilder avoids creating many new objects. (StringBuilder in loop)
StringBuilder modifies the same object without creating new ones, making it faster and more memory efficient for repeated changes.Final Answer:
Option B is better because StringBuilder avoids creating many new objects. -> Option BQuick Check:
Use StringBuilder for repeated string changes in loops [OK]
- Using String concatenation in loops thinking it's fast
- Ignoring immutability of String
- Assuming simpler code is always better
Ready to prove it?
Pass the test and this pattern moves unknown
