PSR-4 directory mapping in PHP - Time & Space Complexity
Let's see how the time to find a PHP class file grows when using PSR-4 directory mapping.
We want to know how the file lookup time changes as the number of classes grows.
Analyze the time complexity of the following PSR-4 autoloader snippet.
function loadClass($className) {
$prefix = 'App\\';
$baseDir = __DIR__ . '/src/';
if (str_starts_with($className, $prefix)) {
$relativeClass = substr($className, strlen($prefix));
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
}
}
This code maps a class name to a file path and loads it if found.
Look for repeated steps when loading classes.
- Primary operation: Checking if the class name starts with the prefix and converting namespace separators to directory separators.
- How many times: Once per class load request.
The time to load a class depends on how long it takes to build the file path and check if the file exists.
| Input Size (number of classes) | Approx. Operations |
|---|---|
| 10 | 10 file path builds and checks |
| 100 | 100 file path builds and checks |
| 1000 | 1000 file path builds and checks |
Pattern observation: Each class load requires a direct path build and file check, so operations grow linearly with the number of classes loaded.
Time Complexity: O(1)
This means loading a single class file takes about the same time regardless of how many classes exist, because the path is computed directly.
[X] Wrong: "Loading a class gets slower as more classes are added because it searches through all files."
[OK] Correct: PSR-4 uses a direct mapping from class name to file path, so it does not search all files but directly checks one file.
Understanding how PSR-4 autoloading works and its time complexity shows you know how modern PHP apps efficiently load code on demand.
What if the autoloader had to scan multiple directories for each class? How would the time complexity change?