Singleton pattern in PHP - Time & Space 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.
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 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.
Each call to getInstance() does a quick check and returns the stored instance.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple checks and returns |
| 100 | 100 simple checks and returns |
| 1000 | 1000 simple checks and returns |
Pattern observation: The work grows directly with the number of calls, but each call is very fast.
Time Complexity: O(1)
This means the time to get the Singleton instance is constant for each call after the first creation.
[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.
Understanding how Singleton controls instance creation helps you explain resource management in real projects.
"What if the Singleton created a new instance every time instead of storing one? How would the time complexity change?"