Method overriding in Ruby - Time & Space Complexity
We want to understand how the time it takes to run code changes when we use method overriding in Ruby.
Specifically, we ask: does overriding a method affect how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
class Animal
def speak
"Hello"
end
end
class Dog < Animal
def speak
"Woof!" # Overrides Animal's speak
end
end
animals = [Animal.new, Dog.new, Animal.new]
animals.each { |a| puts a.speak }
This code defines a base class and a subclass that overrides a method. It then calls the method on a list of objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of objects and calling
speakon each. - How many times: Once for each object in the array (3 times here, but could be more).
Each object in the list has its speak method called once. As the list grows, the number of calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The number of method calls grows directly with the number of objects.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects we call the method on.
[X] Wrong: "Overriding a method makes the program slower because it adds extra work."
[OK] Correct: Overriding just changes which code runs, but calling the method still happens once per object, so the time grows the same way.
Understanding how method overriding affects performance helps you explain your code choices clearly and shows you know how programs run as they grow.
What if the speak method called another method inside it that loops over a list? How would the time complexity change?