0
0
PHPprogramming~5 mins

Readonly properties in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Readonly properties
O(n)
Understanding Time Complexity

Let's see how using readonly properties affects the time it takes for a PHP program to run.

We want to know how the program's steps grow when we use readonly properties in objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class User {
    public readonly string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}

$users = [];
for ($i = 0; $i < $n; $i++) {
    $users[] = new User("User" . $i);
}

This code creates $n User objects, each with a readonly name property set once during construction.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a new User object and setting its readonly property.
  • How many times: The loop runs exactly $n times, once per User object.
How Execution Grows With Input

Each new User object takes a fixed amount of time to create and set the readonly property.

Input Size (n)Approx. Operations
10About 10 object creations and property sets
100About 100 object creations and property sets
1000About 1000 object creations and property sets

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as we create more User objects with readonly properties.

Common Mistake

[X] Wrong: "Readonly properties make object creation instant or free."

[OK] Correct: Even though readonly properties cannot be changed later, setting them during construction still takes time for each object created.

Interview Connect

Understanding how readonly properties affect object creation helps you explain performance in real projects where immutability matters.

Self-Check

"What if we added a loop inside the User constructor that runs $m times? How would the time complexity change?"