moriesta
moriesta

Reputation: 1200

custom autoload vs default

which autoload method is faster?

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

Custom autoloader:

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

Default autoloader:

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

Although I've read that default one must be faster, according to my tests the custom method wins. The drawback of default method is that the classes must be all lowercase.

Upvotes: 0

Views: 677

Answers (1)

Basti
Basti

Reputation: 4042

As the documentation says the default auto loader will be faster. If you only search three directories with your custom auto loader and a all your directories in get_include_path(), your custom auto loader might be faster. However that is not a fair comparison.

Upvotes: 1

Related Questions