Press "Enter" to skip to content

Yaf_Loader重构测试

自动加载器在一个大型PHP项目中,往往是最容易被忽视的性能点,因为它一般而言都很简单, 但是它的调用次数确实非常之大。Yaf也不例外,虽然Yaf是C语言写的扩展,但还是可能会占到一个复杂项目1%到3%的耗时,这俩天想了想,总不能天天开会写博客吧,还是写点代码吧?于是乎决定启动重构。:)

经过周末的一番重构,我基本上重写了Yaf_Loader::autoload整条生命期, 目的就是降低内存分配,具体的变化可以看:Refactor Yaf_Loader, 效果咋样? 我们来做个简单的测试:

<?php
error_reporting(0);

$loader = Yaf_Loader::getInstance(__DIR__);

$i = 0;
$start = microtime(true);
while ($i++ < 10000) {
	$classname = "A" . rand(1, 1000000);
	$loader->autoload($classname);
	$classname = "B" . rand(1, 1000000) . "Controller";
	$loader->autoload($classname);
	$classname = "C" . rand(1, 1000000) . "Model";
	$loader->autoload($classname);
	$classname = "D" . rand(1, 1000000) . "Plugin";
	$loader->autoload($classname);
}
echo "Time: " , microtime(true) - $start, "s\n";

这个虽然类文件不存在,但是会走过整个Yaf_Loader::autoload的代码路径,只不过在最后载入文件的时候会失败,并不影响我们整体的性能对比测试。

重构前的Yaf_Loader:

Time: 0.5350558757782s

重构后的Yaf_Loader:

Time: 0.48561215400696s

性能提升了将近10% :)

7 Comments

  1. smash karts
    smash karts June 10, 2021

    這絕對是一篇包含我正在尋找的有價值信息的文章。 因此,我非常感謝您為撰寫此信息所做的努力。

  2. Area 52
    Area 52 May 18, 2021

    I’ve really been having problems with the autoloader. Thanks for this!

  3. cookie clicker
    cookie clicker February 23, 2021

    这俩天想,了想,这俩天,想了想,

  4. shudun
    shudun March 9, 2020

    原来鸟哥 也这样测试性能啊 😂

    • laruence
      laruence March 9, 2020

      小改造,简单测一测意思意思就行啦 :)

Comments are closed.