Why Ruby prefers iterators over loops - Performance Analysis
We want to see how Ruby's way of repeating tasks with iterators compares to using loops.
How does the time it takes grow when we use iterators versus loops?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
puts num * 2
end
# vs
for num in numbers
puts num * 2
end
This code prints each number doubled, once using an iterator and once using a loop.
Both the iterator and the loop go through each item in the list one by one.
- Primary operation: Visiting each element to print its double.
- How many times: Exactly once per element in the list.
As the list gets bigger, the number of times we print doubles grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Iterators are slower than loops because they add extra steps."
[OK] Correct: Both do the same main work of visiting each item once, so their time grows the same way.
Understanding how iterators and loops perform helps you explain your choices clearly and shows you know how code runs as data grows.
"What if we used nested iterators to go through a list of lists? How would the time complexity change?"