0
0
PHPprogramming~5 mins

Object instantiation with new in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object instantiation with new
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

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
1010 object creations
100100 object creations
10001000 object creations

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

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of objects, the time to create them roughly doubles too.

Common Mistake

[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.

Interview Connect

Understanding how object creation time grows helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if the constructor of Item did some heavy work like reading a file? How would the time complexity change?"