2012-03-04 143 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