String concatenation behavior in C Sharp (C#) - Time & Space Complexity
When we join strings together in C#, the way we do it affects how long the program takes to run.
We want to know how the time to combine strings grows as we add more pieces.
Analyze the time complexity of the following code snippet.
string result = "";
string[] words = new string[] {"a", "b", "c", "d", "e"};
foreach (string word in words)
{
result += word;
}
This code joins all words in the array into one string by adding each word to the result one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one string to another inside a loop.
- How many times: Once for each word in the array.
Each time we add a word, the program copies the whole current string and the new word to make a new string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than the number of words because each addition copies a longer string.
Time Complexity: O(n²)
This means the time to join strings grows roughly with the square of the number of strings.
[X] Wrong: "Adding strings in a loop always takes time proportional to the number of strings (O(n))."
[OK] Correct: Each addition copies the whole current string, so the work adds up more than just once per string.
Understanding how string joining works helps you write faster code and explain your choices clearly in real projects.
"What if we used a StringBuilder instead of += inside the loop? How would the time complexity change?"