0
0
Javaprogramming~15 mins

String vs StringBuilder in Java - Performance Comparison

Choose your learning style8 modes available
scheduleTime Complexity: String vs StringBuilder
O(n^2) for String concatenation, O(n) for StringBuilder
menu_bookUnderstanding Time Complexity

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?

code_blocksScenario Under Consideration

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.

repeatIdentify Repeating Operations

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.
search_insightsHow Execution Grows With Input

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)
10About 55 copiesAbout 10 appends
100About 5,050 copiesAbout 100 appends
1000About 500,500 copiesAbout 1000 appends

Pattern observation: String concatenation work grows much faster than StringBuilder as n grows.

cards_stackFinal Time Complexity

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.

chat_errorCommon Mistake

[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.

business_centerInterview Connect

Knowing when to use StringBuilder shows you understand how code speed changes with input size, a key skill in programming.

psychology_altSelf-Check

"What if we used StringBuffer instead of StringBuilder? How would the time complexity change?"