StringBuilder methods and performance in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with text in C#, using StringBuilder can affect how fast your program runs.
We want to see how the time it takes changes as the text gets longer.
Analyze the time complexity of the following code snippet.
StringBuilder sb = new 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 from 0 up to n-1 one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time appending a small string.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of append operations grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n * m)
This means the time to build the string grows directly with the number of items added and the average length of each appended string.
[X] Wrong: "Using StringBuilder.Append inside a loop is slow because it copies the whole string every time."
[OK] Correct: StringBuilder is designed to avoid copying the entire string on each append, so appending is fast and grows linearly, not quadratically.
Understanding how StringBuilder works helps you write efficient code when dealing with many string changes, a useful skill in many programming tasks.
"What if we replaced StringBuilder with simple string concatenation inside the loop? How would the time complexity change?"
Practice
StringBuilder over regular string concatenation in C#?Solution
Step 1: Understand string immutability in C#
Regular strings cannot be changed once created, so concatenation creates new strings each time.Step 2: How StringBuilder works
StringBuilder changes the text in place without making new copies, which is faster for many changes.Final Answer:
It modifies the string without creating new string copies, improving performance. -> Option AQuick Check:
StringBuilder avoids new copies [OK]
- Thinking StringBuilder sorts or encrypts text
- Believing StringBuilder changes case automatically
- Confusing StringBuilder with regular string methods
StringBuilder named sb?Solution
Step 1: Recall StringBuilder methods
Append is the method used to add text at the end of the current content.Step 2: Check method names
Add and Concat are not valid StringBuilder methods; Insert adds text at a specific position, not at the end.Final Answer:
sb.Append("Hello"); -> Option AQuick Check:
Append adds text at end [OK]
- Using Add() which does not exist
- Confusing Insert() with Append()
- Trying to use Concat() on StringBuilder
var sb = new System.Text.StringBuilder("Hi");
sb.Append(" there");
sb.Replace("Hi", "Hello");
sb.Remove(5, 1);
Console.WriteLine(sb.ToString());Solution
Step 1: Trace Append and Replace
Start with "Hi", Append adds " there" -> "Hi there". Replace "Hi" with "Hello" -> "Hello there".Step 2: Apply Remove
Remove(5,1) removes 1 character at index 5 (0-based). Index 5 is the space between "Hello" and "there", so removing it joins words -> "Hellothere".Final Answer:
Hellothere -> Option CQuick Check:
Remove space at index 5 = "Hellothere" [OK]
- Forgetting zero-based index in Remove
- Assuming Replace changes all occurrences incorrectly
- Not converting StringBuilder to string before printing
var sb = new System.Text.StringBuilder();
sb.Append("Start");
sb.Remove(10, 3);
Console.WriteLine(sb.ToString());Solution
Step 1: Check Remove parameters
Remove(10, 3) tries to remove 3 characters starting at index 10, but current string length is 5 ("Start").Step 2: Understand exception
Removing beyond string length causes ArgumentOutOfRangeException at runtime.Final Answer:
Remove method call will throw an ArgumentOutOfRangeException. -> Option DQuick Check:
Remove index out of range = Exception [OK]
- Assuming Remove silently ignores invalid indexes
- Thinking Append is incorrect here
- Believing ToString needs no parentheses
StringBuilder. Which code snippet is the most efficient and correct?Solution
Step 1: Appending comma after each number then removing trailing
Appends number and comma each time, then removes last comma. Remove call adds overhead.Step 2: Conditional comma append
Appends number, then comma only if not last number. Avoids extra Remove call, more efficient and clear.Step 3: Analyze options B and C
B appends comma after last number, no removal, so extra comma remains. C hardcodes string, no loop, less flexible.Final Answer:
sb.Append(i); if(i < 5) sb.Append(","); -> Option BQuick Check:
Append comma conditionally [OK]
- Leaving trailing comma without removal
- Hardcoding string instead of looping
- Removing characters unnecessarily
