0
0
PHPprogramming~5 mins

Instanceof operator in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Instanceof operator
O(n)
Understanding Time Complexity

Let's see how the time it takes to check if an object is an instance of a class changes as the program runs.

We want to know how the cost of using the instanceof operator grows with the number of checks.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal {}
class Dog extends Animal {}

$dogs = [];
for ($i = 0; $i < $n; $i++) {
    $dogs[] = new Dog();
}

foreach ($dogs as $dog) {
    if ($dog instanceof Animal) {
        // do something
    }
}
    

This code creates many Dog objects and checks if each one is an instance of Animal.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop that checks instanceof for each object.
  • How many times: It runs once for every object in the array, so n times.
How Execution Grows With Input

Each new object adds one more check. So if you double the objects, you double the checks.

Input Size (n)Approx. Operations
1010 instanceof checks
100100 instanceof checks
10001000 instanceof checks

Pattern observation: The number of checks grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to check all objects grows in a straight line as you add more objects.

Common Mistake

[X] Wrong: "The instanceof check is slow and grows exponentially with more objects."

[OK] Correct: Each instanceof check is simple and constant time; the total time grows only as you add more objects, not faster.

Interview Connect

Understanding how instanceof checks scale helps you write efficient code when working with many objects, a useful skill in real projects.

Self-Check

"What if we nested instanceof checks inside another loop over the same objects? How would the time complexity change?"