- URL: https://www.laruence.com/en/2020/03/09/5395.html
- Please include attribution when republishing.
In a large PHP project, the autoloader is often the most overlooked performance point, because it's generally very simple — yet it gets called an enormous number of times. Yaf is no exception: even though Yaf is a C-language extension, it can still account for 1% to 3% of the time in a complex project. After thinking about it for a couple of days — I can't just hold meetings and write blog posts every day, I should actually write some code — I decided to kick off a refactor. 🙂
Over the weekend, I essentially rewrote the entire lifecycle of Yaf_Loader::autoload, with the goal of reducing memory allocation. The specific changes are in: Refactor Yaf_Loader. How did it turn out? Let's do a simple test:
<?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";
Although these class files don't exist, the code still walks the entire Yaf_Loader::autoload path — it just fails at the final file-loading step, which doesn't affect our overall performance comparison.
Yaf_Loader before the refactor:
Time: 0.5350558757782s
Yaf_Loader after the refactor:
Time: 0.48561215400696s
Performance improved by almost 10% 🙂
Be First to Comment