Table of Contents

PHP RFC: Autoload Classmap

Introduction

Currently, autoloading requires invoking a userland function that is then responsible for performing its own logic to determine the class location on disk, and including that file before returning.

Production autoloaders (notably composer) already generate a classmap to accelerate their own lookups. By allowing this lookup and file inclusion to be performed within the engine itself we can potentially save a large number of calls to the userland autoloader per request.

Proposal

This RFC would introduce a new mechanism for autoloading classes via an internal classmap loader, that can be configured once per request by passing an associative array mapping each lowercase class name to its path on disk.

This proposal is written with the names autoload_xx rather than spl_autoload_ as an independent RFC will be proposed to alias the existing SPL autoload functions to simply autoload_xx (or whatever is eventually agreed upon). If that RFC fails, but this one passes, the implementation would use spl_autoload_xx names instead.

/* Sets the internal autoloader to use the given classmap */
autoload_set_classmap(array $mapping): void {}
 
/* Returns the existing classmap (or an empty array) */
autoload_get_classmap(): array {}

Rules:

The autoloader will:

If the classmap is not set, or the class name cannot be found within the classmap, the autoloader will continue to perform its traditional behaviour of iterating over the functions specified by spl_autoload_register.

Performance

Testing suggests that autoloading through an internal classmap delivers around 5% performance increase vs a userland function call (e.g. composer).

This is 5% of the cost of the autoloading, and not the execution as a whole. Testing was performed by creating 50,000 empty classes each in an individual file, and then autoloading every one of them in a loop. Amount of classes was purely to help reduce noise.

Average for internal classmap was 0.295 vs 0.313 for spl_autoload_register representing 5.9% difference (in autoload performance only).

Proposed PHP Version(s)

PHP 8.1

Proposed Voting Choices

Accept feature as proposed Yes / No

Implementation

https://github.com/php/php-src/pull/6776