Readonly properties in PHP - Time & Space 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.
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 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.
Each new User object takes a fixed amount of time to create and set the readonly property.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations and property sets |
| 100 | About 100 object creations and property sets |
| 1000 | About 1000 object creations and property sets |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to run grows in a straight line as we create more User objects with readonly properties.
[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.
Understanding how readonly properties affect object creation helps you explain performance in real projects where immutability matters.
"What if we added a loop inside the User constructor that runs $m times? How would the time complexity change?"