自定义自动加载与默认


custom autoload vs default

哪种自动加载方法更快?

    private $_directoriesToLook = array("framework/", "models/", "controllers/");

自定义自动加载器:

    private function customAutoloader($class_name)
    {
        if(class_exists($class_name))
            return true;
        foreach($this->_directoriesToLook as $directory)
        {
            $files = scandir($directory);
            if(in_array($class_name.".php", $files))
            {
                require_once($directory.$class_name.".php");
                return true;
            }
        }
        return false;
    }
    spl_autoload_register(array($this, "customAutoloader"));

默认自动加载器:

set_include_path(get_include_path().PATH_SEPARATOR.implode(PATH_SEPARATOR, $this->_directoriesToLook));
spl_autoload_extensions(".php");  
spl_autoload_register();

尽管我读到默认方法必须更快,但根据我的测试,自定义方法获胜。默认方法的缺点是类必须全部小写。

正如文档所说,默认的自动加载器会更快。如果您只使用自定义自动加载器搜索三个目录,并在get_include_path()中搜索所有目录,那么您的自定义自动加载器可能会更快。然而,这不是一个公平的比较。