Heredoc syntax for multiline strings in Ruby - Time & Space Complexity
We want to understand how the time it takes to create a multiline string using heredoc changes as the string gets longer.
How does the work grow when the string has more lines?
Analyze the time complexity of the following code snippet.
text = <<~HEREDOC
This is line one.
This is line two.
This is line three.
HEREDOC
puts text
This code creates a multiline string using heredoc syntax and then prints it.
- Primary operation: Reading each line of the multiline string to build the final string.
- How many times: Once for each line in the heredoc block.
As the number of lines in the heredoc increases, the time to create the string grows roughly in direct proportion.
| Input Size (lines) | Approx. Operations |
|---|---|
| 10 | About 10 operations to read and store lines |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows steadily as more lines are added, roughly one step per line.
Time Complexity: O(n)
This means the time to create the multiline string grows in a straight line with the number of lines.
[X] Wrong: "Creating a multiline string with heredoc takes the same time no matter how many lines it has."
[OK] Correct: Each line must be read and stored, so more lines mean more work and more time.
Understanding how string creation time grows helps you write efficient code when working with large text blocks, a useful skill in many programming tasks.
"What if we changed the heredoc to use string concatenation line by line? How would the time complexity change?"