0
0
PHPprogramming~5 mins

Readonly classes in PHP - Time & Space Complexity

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

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

We want to know how the program's steps grow when working with readonly classes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


final readonly class UserData {
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

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

This code creates many readonly UserData objects and stores them in an array.

Identify Repeating Operations

Look for loops or repeated actions.

  • Primary operation: Creating a new UserData object inside a loop.
  • How many times: The loop runs n times, so n objects are created.
How Execution Grows With Input

Each new object takes a small, fixed amount of time to create.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

As n grows, the total work grows in a straight line with it.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all readonly objects grows directly with the number of objects.

Common Mistake

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

[OK] Correct: Readonly means properties can't change after creation, but creating each object still takes time proportional to how many you make.

Interview Connect

Understanding how object creation scales helps you write clear and efficient code, a skill valued in many coding discussions.

Self-Check

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