0
0
Rubyprogramming~5 mins

File.readlines for line-by-line in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: File.readlines for line-by-line
O(n)
Understanding Time Complexity

When reading a file line by line using File.readlines, it's important to know how the time to read grows as the file gets bigger.

We want to understand how the number of lines affects the time it takes to read them all.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

lines = File.readlines("example.txt")
lines.each do |line|
  puts line.strip
end

This code reads all lines from a file into an array, then goes through each line to print it without extra spaces.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading each line from the file and then iterating over each line.
  • How many times: Once for each line in the file.
How Execution Grows With Input

As the number of lines grows, the time to read and process them grows roughly the same way.

Input Size (n)Approx. Operations
10About 10 reads and 10 prints
100About 100 reads and 100 prints
1000About 1000 reads and 1000 prints

Pattern observation: The work grows directly with the number of lines; double the lines, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to read and process the file grows in a straight line with the number of lines.

Common Mistake

[X] Wrong: "Reading lines with File.readlines is instant no matter the file size."

[OK] Correct: Reading each line takes time, so bigger files take longer to read line by line.

Interview Connect

Understanding how file reading scales helps you write programs that handle big files without surprises.

Self-Check

"What if we used File.foreach instead of File.readlines? How would the time complexity change?"