Readonly classes in PHP - Time & Space 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.
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.
Look for loops or repeated actions.
- Primary operation: Creating a new UserData object inside a loop.
- How many times: The loop runs
ntimes, sonobjects are created.
Each new object takes a small, fixed amount of time to create.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
As n grows, the total work grows in a straight line with it.
Time Complexity: O(n)
This means the time to create all readonly objects grows directly with the number of objects.
[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.
Understanding how object creation scales helps you write clear and efficient code, a skill valued in many coding discussions.
"What if we added a nested loop inside the constructor that runs m times? How would the time complexity change?"