String creation (single and double quotes) in Ruby - Time & Space Complexity
We want to see how long it takes to create strings using single or double quotes in Ruby.
How does the time needed change when we make bigger or more strings?
Analyze the time complexity of the following code snippet.
10.times do
s1 = 'hello'
s2 = "world"
end
This code creates two strings inside a loop that runs 10 times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating two strings each loop cycle.
- How many times: 10 times because of the loop.
Each time the loop runs, it makes two new strings. So if the loop runs more, the work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 string creations |
| 100 | 200 string creations |
| 1000 | 2000 string creations |
Pattern observation: The work grows directly with the number of loop runs.
Time Complexity: O(n)
This means the time to create strings grows in a straight line as the loop count grows.
[X] Wrong: "Creating strings with single quotes is faster than double quotes, so it changes time complexity."
[OK] Correct: Both create strings in constant time each; the difference is tiny and does not affect how time grows with input size.
Understanding how simple operations like string creation scale helps you explain code efficiency clearly and confidently.
"What if we created strings inside a nested loop? How would the time complexity change?"