0
0
PHPprogramming~5 mins

PSR-4 directory mapping in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: PSR-4 directory mapping
O(1)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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

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
1010 file path builds and checks
100100 file path builds and checks
10001000 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.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how PSR-4 autoloading works and its time complexity shows you know how modern PHP apps efficiently load code on demand.

Self-Check

What if the autoloader had to scan multiple directories for each class? How would the time complexity change?