0
0
C Sharp (C#)programming~5 mins

StringBuilder and why it exists in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: StringBuilder and why it exists
O(n * m)
Understanding Time Complexity

When working with text in C#, how fast your program runs can change a lot depending on how you build strings.

We want to see why StringBuilder helps and how its speed changes as text grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var sb = new System.Text.StringBuilder();
for (int i = 0; i < n; i++)
{
    sb.Append(i.ToString());
}
string result = sb.ToString();
    

This code builds a long string by adding numbers one by one using StringBuilder.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs n times, each time appending text to StringBuilder.
  • How many times: Exactly n times, once per number added.
How Execution Grows With Input

As n grows, the number of append actions grows directly with n.

Input Size (n)Approx. Operations
10About 10 appends
100About 100 appends
1000About 1000 appends

Pattern observation: The work grows steadily and directly with the number of items added.

Final Time Complexity

Time Complexity: O(n * m)

This means the time to build the string grows linearly with the number of items added and the average length of each item.

Common Mistake

[X] Wrong: "Using + to add strings is just as fast as StringBuilder."

[OK] Correct: Adding strings with + creates new strings each time, making work grow much faster than with StringBuilder.

Interview Connect

Understanding how StringBuilder helps with many text additions shows you know how to write faster, smarter code when working with strings.

Self-Check

What if we replaced StringBuilder with simple string concatenation inside the loop? How would the time complexity change?