0
0
PHPprogramming~5 mins

Why inheritance is needed in PHP - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why inheritance is needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Imagine changing the number of Dog objects created.

Input Size (n)Approx. Operations
1010 creations + 10 speak calls = 20 operations
100100 creations + 100 speak calls = 200 operations
10001000 creations + 1000 speak calls = 2000 operations

Pattern observation: The total work grows directly with the number of objects; doubling objects doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of objects created and methods called.

Common Mistake

[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.

Interview Connect

Understanding how inheritance affects time helps you explain your design choices clearly and shows you know how code structure relates to performance.

Self-Check

"What if we added a loop inside the speak() method that runs n times? How would the time complexity change?"