Final classes and methods in PHP - Time & Space Complexity
Let's see how using final classes and methods affects how long a PHP program takes to run.
We want to know if marking classes or methods as final changes the speed as the program grows.
Analyze the time complexity of the following code snippet.
final class Calculator {
public function add(array $numbers): int {
$sum = 0;
foreach ($numbers as $num) {
$sum += $num;
}
return $sum;
}
}
$calc = new Calculator();
$result = $calc->add([1, 2, 3, 4, 5]);
This code defines a final class with a method that adds numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array to add numbers.
- How many times: Once for each number in the input array.
As the number of numbers grows, the time to add them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Making a class or method final makes the code run faster."
[OK] Correct: Final only stops changes in code structure; it does not change how many steps the program takes.
Understanding time complexity helps you explain how your code behaves as it grows, which is a useful skill in many coding discussions.
"What if the add method used recursion instead of a loop? How would the time complexity change?"