0
0
PHPprogramming~5 mins

Factory pattern in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Factory pattern
O(n)
Understanding Time Complexity

We want to understand how the time it takes to create objects using the factory pattern changes as we create more objects.

How does the work grow when we ask the factory to make many objects?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Car {
    public function drive() {
        echo "Driving a car\n";
    }
}

class CarFactory {
    public function createCar() {
        return new Car();
    }
}

$factory = new CarFactory();
for ($i = 0; $i < $n; $i++) {
    $car = $factory->createCar();
    $car->drive();
}
    

This code creates $n car objects using a factory and calls a method on each.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a new Car object inside the loop.
  • How many times: Exactly $n times, once per loop iteration.
How Execution Grows With Input

Each time we increase $n, the number of cars created grows the same amount.

Input Size (n)Approx. Operations
1010 car creations and drives
100100 car creations and drives
10001000 car creations and drives

Pattern observation: The work grows directly in proportion to the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and use cars grows linearly as we ask for more cars.

Common Mistake

[X] Wrong: "Using a factory makes object creation instant or constant time no matter how many objects."

[OK] Correct: Each object still needs to be created one by one, so time grows with the number of objects.

Interview Connect

Understanding how object creation scales helps you explain design choices clearly and shows you think about efficiency in real code.

Self-Check

"What if the factory cached and reused objects instead of creating new ones each time? How would the time complexity change?"