Why inheritance is needed in PHP - Performance Analysis
We want to understand how using inheritance affects the time it takes for a program to run.
Specifically, we ask: does inheritance change how the program's work grows as input grows?
Analyze the time complexity of the following PHP code using inheritance.
class Animal {
public function speak() {
echo "Animal sound\n";
}
}
class Dog extends Animal {
public function speak() {
echo "Bark\n";
}
}
$dogs = [];
for ($i = 0; $i < 5; $i++) {
$dogs[] = new Dog();
}
foreach ($dogs as $dog) {
$dog->speak();
}
This code creates several Dog objects that inherit from Animal and calls their speak method.
Look at what repeats in the code.
- Primary operation: Creating Dog objects and calling speak() on each.
- How many times: The loop runs 5 times, so 5 objects are created and 5 speak calls happen.
Imagine changing the number of Dog objects created.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations + 10 speak calls = 20 operations |
| 100 | 100 creations + 100 speak calls = 200 operations |
| 1000 | 1000 creations + 1000 speak calls = 2000 operations |
Pattern observation: The total work grows directly with the number of objects; doubling objects doubles work.
Time Complexity: O(n)
This means the time grows in a straight line with the number of objects created and methods called.
[X] Wrong: "Inheritance makes the program slower because it adds extra steps."
[OK] Correct: Inheritance itself does not add loops or repeated work; it just organizes code. The time depends on how many objects and calls you make, not on inheritance alone.
Understanding how inheritance affects time helps you explain your design choices clearly and shows you know how code structure relates to performance.
"What if we added a loop inside the speak() method that runs n times? How would the time complexity change?"