2012-03-04 142 views
0

哪种自动加载方法更快?自定义自动加载vs默认

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(); 

虽然我读过,默认一个必须要快,根据我的测试自定义方法获胜。 缺省方法的缺点是类必须全部小写。

回答

1

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

+0

默认方法的问题是它不允许使用驼峰类/文件名。 – Acute 2012-03-04 18:21:47

+1

我不会打扰来自默认自动加载器的轻微性能增益。只要做你的自定义自动装载机与骆驼案件的支持。可读代码比获得几毫秒的执行时间更重要。 – Basti 2012-03-04 18:27:59