Why interfaces are needed in PHP - Performance Analysis
We want to understand how using interfaces affects the time it takes for a program to run.
Specifically, we ask: does adding interfaces change how fast our code runs as it grows?
Analyze the time complexity of the following code snippet.
interface Logger {
public function log(string $message): void;
}
class FileLogger implements Logger {
public function log(string $message): void {
// write message to a file
}
}
function process(Logger $logger, array $items): void {
foreach ($items as $item) {
$logger->log("Processing: " . $item);
}
}
This code defines an interface and a class that implements it. The process function uses the interface to log messages for each item.
- Primary operation: Looping through each item in the array.
- How many times: Once for each item in the input array.
As the number of items grows, the number of log calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 log calls |
| 100 | 100 log calls |
| 1000 | 1000 log calls |
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 number of items processed.
[X] Wrong: "Using interfaces makes the code slower because of extra layers."
[OK] Correct: Interfaces define rules but do not add loops or repeated work. The main time depends on how many items you process, not on the interface itself.
Understanding that interfaces help organize code without slowing it down shows you know how to write clean and efficient programs. This skill is useful in many real projects.
"What if the process function called two different interface methods inside the loop? How would the time complexity change?"