0
0
PHPprogramming~5 mins

Singleton pattern in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Singleton pattern
O(1)
Understanding Time Complexity

Let's explore how the time cost grows when using the Singleton pattern in PHP.

We want to know how the program's steps increase as we create or access the Singleton instance more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Singleton {
    private static ?Singleton $instance = null;

    private function __construct() {}

    public static function getInstance(): Singleton {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

$single = Singleton::getInstance();

This code creates a Singleton class that only allows one instance to be created and returns it on request.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking if the instance exists and returning it.
  • How many times: Each time getInstance() is called.
How Execution Grows With Input

Each call to getInstance() does a quick check and returns the stored instance.

Input Size (n)Approx. Operations
1010 simple checks and returns
100100 simple checks and returns
10001000 simple checks and returns

Pattern observation: The work grows directly with the number of calls, but each call is very fast.

Final Time Complexity

Time Complexity: O(1)

This means the time to get the Singleton instance is constant for each call after the first creation.

Common Mistake

[X] Wrong: "Creating the Singleton instance is slow every time I call getInstance()."

[OK] Correct: The instance is created only once; later calls just return the stored object quickly.

Interview Connect

Understanding how Singleton controls instance creation helps you explain resource management in real projects.

Self-Check

"What if the Singleton created a new instance every time instead of storing one? How would the time complexity change?"