开发者

Which is a better PHP autoload method?

Would the second autoload method I have below be better performance?

<?php

// regular __autoload function
function __autoload( $name )
{
     include( $class . '.php' );

}


// SPL autoload
spl_autoload_register("MyClass::Autoloader");
class MyClass
{
    public static function Autoloader($class)
    {
        // list of classes and their location
        $classes = array();
        $classes['spooncookie'] = 'cookie/cookie.php';
        $classes['spoondatabase'] = 'database/database.php';
        $classes['spoondatagrid'] = 'datagrid/datagrid.php';
     开发者_开发知识库   $classes['spoondatagridcolumn'] = 'datagrid/column.php';
        $classes['ispoondatagridpaging'] = 'datagrid/paging.php';
        // ....list of all the other class files.......    
        if(isset($classes[$class])){
            include( $classes[$class] );
        }
    }

}

?>


The best way to get an accurate idea of which will give the best performance for your own usage is to test each of them. As a general rule, different methods of autoloading will be optimal in different scenarios, factors include: how many files/classes you have in total, how deep the directory structure is, and how many classes you will load on average per request. The key point behind using an autoloader isn't to make your code run more quickly, but to improve how quickly you can write the code in the first place.

For production code I really would recommend going with a well used autoloader from a framework instead of rolling your own, at least to start with. and then maybe modifying it later if you know its the bottleneck and can be improved.

As a side note, have you seen this? http://weierophinney.net/matthew/archives/245-Autoloading-Benchmarks.html

EDIT:


Unless you have identified your autoloader (and the underlying filesystem poking and prodding) as a performance bottleneck, you really shouldn't worry about it. Profile, profile, profile! Autoloaders can be a real drag, but you are likely to find a larger performance boost elsewhere by actually benchmarking your code.

To be honest, I'd go for a PSR-0 compliant autoloader for a new project.


I'd be inclined to opt for the spl method on the grounds that certain libraries such as Smarty implement an spl autoloader so using the __autoload method can result in conflicts.

The in-function path checking is a good idea too, because any function that pulls a file into your program is potentially dangerous, especially in an environment with allow_url_fopen enabled! I'd be inclined to go with your SPL function complete with its path checking for these reasons.

One optimisation I might suggest is making your path array static. That should eliminate the overhead of creating the array every time the function is envoked (though in truth such overhead should be pretty tiny anyway)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜