String concatenation in PowerShell - Time & Space Complexity
When we join many pieces of text together in PowerShell, the time it takes can change depending on how many pieces we have.
We want to understand how the work grows as we add more text parts.
Analyze the time complexity of the following code snippet.
$string = ""
for ($i = 0; $i -lt $n; $i++) {
$string += "Item$i "
}
Write-Output $string
This code builds a long string by adding one piece at a time in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a small string to the growing string inside the loop.
- How many times: This happens once for each of the n items.
Each time we add a piece, PowerShell creates a new string by copying the old one and adding the new part.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copy steps |
| 100 | About 5050 copy steps |
| 1000 | About 500,500 copy steps |
Pattern observation: The work grows much faster than the number of items; it grows roughly like the square of n.
Time Complexity: O(n²)
This means if you double the number of pieces, the work to join them grows about four times.
[X] Wrong: "Adding strings in a loop always takes time proportional to the number of items (O(n))."
[OK] Correct: Each addition copies the whole string so far, making the total work grow much faster than just the number of items.
Understanding how string joining works helps you write scripts that run faster and handle more data smoothly.
"What if we used an array to collect pieces first, then joined them all at once at the end? How would the time complexity change?"