0
0
PHPprogramming~5 mins

Final classes and methods in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Final classes and methods
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of numbers grows, the time to add them grows too.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding time complexity helps you explain how your code behaves as it grows, which is a useful skill in many coding discussions.

Self-Check

"What if the add method used recursion instead of a loop? How would the time complexity change?"