关于composer:composer-autoload自动加载性能优化-dumpautoload

9次阅读

共计 4272 个字符,预计需要花费 11 分钟才能阅读完成。

composer 提供的 autoload 机制使得咱们组织代码和引入新类库十分不便,然而也使我的项目的性能降落了不少。

composer autoload 慢的次要起因在于来自对 PSR-0 和 PSR-4 的反对,加载器失去一个类名时须要到文件系统里查找对应的类文件地位,能够看到 PSR-4 或者 PSR-0 的主动加载都是一件很累人的事儿。根本是个 O(n2) 的复杂度。另外有一大堆 is_file 之类的 IO 操作所以性能堪忧。所以明天咱们就来聊聊 composer 主动加载的优化,聊之前咱们先来简略说一下 composer 主动加载的原理。以下是相干局部源码:

<php

class ClassLoader
{
    private $vendorDir;

    // PSR-4
    private $prefixLengthsPsr4 = array();
    private $prefixDirsPsr4 = array();
    private $fallbackDirsPsr4 = array();

    // PSR-0
    private $prefixesPsr0 = array();
    private $fallbackDirsPsr0 = array();

    private $useIncludePath = false;
    private $classMap = array();
    private $classMapAuthoritative = false;
    private $missingClasses = array();
    private $apcuPrefix;

    private static $registeredLoaders = array();

    public function __construct($vendorDir = null)
    {$this->vendorDir = $vendorDir;}
    /**
     * Finds the path to the file where the class is defined.
     *
     * @param string $class The name of the class
     *
     * @return string|false The path if found, false otherwise
     */
    public function findFile($class)
    {
        // class map lookup
        if (isset($this->classMap[$class])) {return $this->classMap[$class];
        }
        if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {return false;}
        if (null !== $this->apcuPrefix) {$file = apcu_fetch($this->apcuPrefix.$class, $hit);
            if ($hit) {return $file;}
        }

        $file = $this->findFileWithExtension($class, '.php');

        // Search for Hack files if we are running on HHVM
        if (false === $file && defined('HHVM_VERSION')) {$file = $this->findFileWithExtension($class, '.hh');
        }

        if (null !== $this->apcuPrefix) {apcu_add($this->apcuPrefix.$class, $file);
        }

        if (false === $file) {
            // Remember that this class does not exist.
            $this->missingClasses[$class] = true;
        }

        return $file;
    }
    private function findFileWithExtension($class, $ext)
    {
        // PSR-4 lookup
        $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;

        $first = $class[0];
        if (isset($this->prefixLengthsPsr4[$first])) {
            $subPath = $class;
            while (false !== $lastPos = strrpos($subPath, '\\')) {$subPath = substr($subPath, 0, $lastPos);
                $search = $subPath . '\\';
                if (isset($this->prefixDirsPsr4[$search])) {$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
                    foreach ($this->prefixDirsPsr4[$search] as $dir) {if (file_exists($file = $dir . $pathEnd)) {return $file;}
                    }
                }
            }
        }

        // PSR-4 fallback dirs
        foreach ($this->fallbackDirsPsr4 as $dir) {if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {return $file;}
        }

        // PSR-0 lookup
        if (false !== $pos = strrpos($class, '\\')) {
            // namespaced class name
            $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
                . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
        } else {
            // PEAR-like class name
            $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
        }

        if (isset($this->prefixesPsr0[$first])) {foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {if (0 === strpos($class, $prefix)) {foreach ($dirs as $dir) {if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {return $file;}
                    }
                }
            }
        }

        // PSR-0 fallback dirs
        foreach ($this->fallbackDirsPsr0 as $dir) {if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {return $file;}
        }

        // PSR-0 include paths.
        if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {return $file;}

        return false;
    }


}
 
?>

从源码中咱们看出,Compsoer\ClassLoader 会优先查看 autoload_classmap 中所有生成的注册类。如果在 classmap 中没有发现再 fallback 到 psr-4 而后 psr-0。所以咱们就从 classmap 动手。

1. 第一层级 (Level-1) 优化:生成 classmap
如何运行:

执行命令 composer dump-autoload -o(-o 等同于 --optimize)

原理:

这个命令的实质是将 PSR-4/PSR-0 的规定转化为了 classmap 的规定,因为 classmap 中蕴含了所有类名与类文件门路的对应关系,所以加载器不再须要到文件系统中查找文件了。能够从 classmap 中间接找到类文件的门路。

注意事项:

这个命令并没有思考到当在 classmap 中找不到指标类时的状况,当加载器找不到指标类时,仍旧会依据 PSR-4/PSR-0 的规定去文件系统中查找。

2. 第二层级 (Level-2/A) 优化:权威的(Authoritative)classmap

如何运行:

执行命令 composer dump-autoload -a(-a 等同于 --classmap-authoritative)

原理

执行这个命令隐含的也执行了 Level-1 的命令,即同样也是生成了 classmap,区别在于当加载器在 classmap 中找不到指标类时,不会再去文件系统中查找(即隐含的认为 classmap 中就是所有非法的类,不会有其余的类了,除非法调用)

注意事项

如果你的我的项目在运行时会生成类,应用这个优化策略会找不到这些新生成的类。

3. 第二层级 (Level-2/B) 优化:应用 APCu cache

如何运行:

执行命令 composer dump-autoload --apcu

原理:

应用这个策略须要装置 apcu 扩大。
apcu 能够了解为一块内存,并且能够在多过程中共享。
这种策略是为了在 Level-1 中 classmap 中找不到指标类时,将在文件系统中找到的后果存储到共享内存中,当下次再查找时就能够从内存中间接返回,不必再去文件系统中再次查找。

在生产环境下,这个策略个别也会与 Level-1 一起应用,执行 composer dump-autoload -o –apcu, 这样,即便生产环境下生成了新的类,只须要文件系统中查找一次即可被缓存,补救了 Level-2/A 的缺点。

如何抉择优化策略?

要依据本人我的项目的理论状况来抉择策略,如果你的我的项目在运行时不会生成类文件并且须要 composer 的 autoload 去加载,那么应用 Level-2/A 即可,否则应用 Level-1 及 Level-2/ B 是比拟好的抉择。

几个提醒:
1、Level- 2 的优化根本都是 Level-1 优化的补充,Level-2/A 次要是决定在 classmap 中找不到指标类时是否持续找上来的问题,Level-2/B 次要是在提供了一个缓存机制,将在 classmap 中找不到时,将从文件系统中找到的文件门路缓存起来,减速后续查找的速度。

2、在执行了 Level-2/A 时,示意在 classmap 中找不到不会持续找,此时 Level-2/B 是不会失效的。

3、不管那种状况都倡议要开启 opcache,这会极大的进步类的加载速度,我目测有性能晋升至多 10 倍。

正文完
 0