File.write for writing in Ruby - Time & Space Complexity
When we use File.write in Ruby, we want to know how the time it takes changes as the data size grows.
We ask: How does writing more data affect the time needed?
Analyze the time complexity of the following code snippet.
text = "Hello, world!" * n
File.write("output.txt", text)
This code creates a string repeated n times and writes it to a file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each character of the string to the file.
- How many times: Once for each character in the string, which grows with
n.
As the string gets longer, the time to write grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Writing about 130 characters |
| 100 | Writing about 1,300 characters |
| 1000 | Writing about 13,000 characters |
Pattern observation: Doubling n roughly doubles the work needed to write the file.
Time Complexity: O(n)
This means the time to write grows directly with the size of the data.
[X] Wrong: "Writing a file always takes the same time no matter how big the data is."
[OK] Correct: Writing more data means more characters to save, so it takes longer as the data grows.
Understanding how file writing time grows helps you explain performance in real programs that save data.
"What if we wrote the file in small chunks inside a loop instead of all at once? How would the time complexity change?"