Ensure for cleanup in Ruby - Time & Space Complexity
We want to understand how the time taken by code using ensure changes as input grows.
Specifically, how does the cleanup part affect overall execution time?
Analyze the time complexity of the following code snippet.
def process_items(items)
items.each do |item|
begin
puts "Processing #{item}"
ensure
puts "Cleaning up after #{item}"
end
end
end
process_items([1, 2, 3, 4, 5])
This code processes each item and always runs cleanup code after processing each one.
Look for loops or repeated actions.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the input list.
Each item causes the code inside the loop and the ensure block to run once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 processing + 10 cleanup) |
| 100 | About 200 (100 processing + 100 cleanup) |
| 1000 | About 2000 (1000 processing + 1000 cleanup) |
Pattern observation: The total work grows directly with the number of items, doubling the steps because of the cleanup after each.
Time Complexity: O(n)
This means the time grows in a straight line as the number of items increases, including the cleanup step.
[X] Wrong: "The ensure block runs only once, so it doesn't affect time much."
[OK] Correct: The ensure block runs every time the loop runs, so it adds work proportional to the input size.
Understanding how cleanup code inside loops affects time helps you explain real-world code behavior clearly and confidently.
"What if the cleanup code inside ensure was a separate method called only once after the loop? How would the time complexity change?"