Object instantiation with new in PHP - Time & Space Complexity
When we create new objects in PHP using new, it takes some time to set up each object.
We want to know how the time needed grows as we create more objects.
Analyze the time complexity of the following code snippet.
class Item {
public function __construct() {
// Some setup code
}
}
$items = [];
for ($i = 0; $i < $n; $i++) {
$items[] = new Item();
}
This code creates $n new objects of the Item class and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new
Itemobject inside the loop. - How many times: Exactly
$ntimes, once per loop iteration.
Each new object takes a similar amount of time to create, so total time grows as we add more objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The time grows directly in proportion to the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Creating objects inside a loop is instant and does not affect performance."
[OK] Correct: Each object creation takes some time, so doing it many times adds up and affects total time.
Understanding how object creation time grows helps you write efficient code and explain your reasoning clearly in interviews.
"What if the constructor of Item did some heavy work like reading a file? How would the time complexity change?"