Why file handling matters in Ruby - Performance Analysis
When working with files, it is important to know how the time to read or write grows as the file size changes.
We want to understand how the program's speed changes when handling bigger or smaller files.
Analyze the time complexity of the following code snippet.
File.open('data.txt', 'r') do |file|
file.each_line do |line|
puts line.chomp
end
end
This code reads a file line by line and prints each line without extra spaces.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the file one by one.
- How many times: Once for every line in the file.
As the file gets bigger, the program reads more lines, so it takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 lines | 10 reads and prints |
| 100 lines | 100 reads and prints |
| 1000 lines | 1000 reads and prints |
Pattern observation: The time grows directly with the number of lines; double the lines, double the work.
Time Complexity: O(n)
This means the time to read and print grows in a straight line with the number of lines in the file.
[X] Wrong: "Reading a file always takes the same time no matter how big it is."
[OK] Correct: The program reads each line one by one, so bigger files take more time to process.
Understanding how file size affects reading time helps you write programs that handle data efficiently and predict performance.
"What if we read the whole file at once instead of line by line? How would the time complexity change?"