Super keyword behavior in Ruby - Time & Space Complexity
We want to understand how using the super keyword affects the time it takes for a program to run.
Specifically, how does calling a method from a parent class impact execution as input grows?
Analyze the time complexity of the following Ruby code using super.
class Parent
def process(items)
items.map { |item| item * 2 }
end
end
class Child < Parent
def process(items)
result = super
result.select { |x| x > 10 }
end
end
child = Child.new
child.process([1, 5, 10, 20])
This code doubles each item in a list using the parent method, then filters the doubled items in the child method.
Look for loops or repeated actions in the code.
- Primary operation: Two loops over the list: one in the parent
processmethod (map), and one in the child method (select). - How many times: Each loop runs once over all items, so twice over the input list.
Each item in the input list is processed twice, once for doubling and once for filtering.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 loops x 10 items) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows roughly twice as fast as the input size.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of items.
[X] Wrong: "Using super makes the method twice as slow in a way that changes the overall time complexity."
[OK] Correct: Calling super just adds another loop over the data, so it still grows linearly with input size, not exponentially or worse.
Understanding how method calls like super affect performance helps you explain your code clearly and reason about efficiency in real projects.
What if the parent method used nested loops instead of a single loop? How would the time complexity change?