Are there performance downsides while using autoloading classes in PHP?

百般思念 提交于 2019-12-05 01:53:31
Gfox

This article has some information and benchmarks: PHP autoload performance. Conclusion:

Autoloading does not significantly degrade performance. Include_path lookup, reading and parsing PHP scripts from disk takes much longer time than that bare autoloading logic costs.

Autoloading a class is almost as fast as including the class in the normal way. Switching to autoloading will improve performance in your case, because PHP loads less files and classes.

Autoloading will improve the performance if the script does not have to search the files each time in the filesystem. If you use namespaces you can have a nice mapping of the namespace and class name to a folder and file like Some/Nice/ClassName would map to Some/Nice/ClassName.php.

If you do not use namespaces and have to search through folders I suggest you to create a custom singleton class to include files that allows you to do something like:

App::uses('Some/Nice', 'ClassName');

In Autoload use the registered path and class name to map it to a path and file combining both args from the uses method in my example. This will allow you some namespace like functionality for class loading until you're ready to change your app to use namespaces.

You should use autoloading with cache index of all available classes/files in project.

Example:

$class_cache=array(
    'MyClass'=>'lib/MyClass.php',
    'Item'=>'model/Item.php'
);

function __autoload($class_name) {
 if(array_key_exists($class_name))
   include $class_cache[$class_name];
 else
   throw new Exception("Unable to load $class_name.");
}

You need to keep class list actual or write some generator for $class_cache.

Each include() and require() (and their _oncesiblings) carry a performance penalty on their own. Disk seeks and reads also come at a cost. It really depends on your code, if you are loading 20 classes but use only 2 or 3 at any single point, then it's definitely worth going the autoloading route.

If performance is your main concern, you should look into merging your class files into a single file and instantiate what you need.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!