根据和yak同学的热烈讨论,我根据他的一些理念,短暂的设计了一个函数,主要为了检查到底单文件的include速度快,还是多个文件的速度快。当然,虽然我也早就知道结果了,但是我还是很认真的实现了三个不同的版本。
代码在这里:http://www.oschina.net/code/snippet_57579_3773
三个不同的版本分别说明一下:
1.php
合并多个文件include,如果不存在合并的文件,则逐个读取要合并的文件,并放入同一个数组中,生成合并后的文件,每个文件都给一个时间标记。
再次include的时候,如果存在该文件,则直接include文件,并且继续检查需要加载的文件的最后变更时间,根据最后更新时间来检查文件是否变更,如果变更,则重新生成合并文件。
1.php的性能,6个文件合并后的加载(带时间检查):0.259ms
2.php
这个就是最原始的,每次都重复加载6个文件,没有什么技巧,纯肉。
时间:0.346 - 0.377之间
3.php
这个类似1.php,但是对于已经存在合并的文件检查稍微有些不同,他只检查是否存在标记,不存在标记则重新加载(即不检查文件是否更新,这种模式适合production版本,如果?update_cache=1,强行给更新的url参数,则会强行刷新合并的文件)。
时间:0.133 - 0.15之间
1.php的代码:
<?php
/**
* created by JetBrains PhpStorm, at 11-4-1
* @author Jan
*/
$start = microtime(true);
function cached_file_by_mtime($file_list, $cache_file = 'cached.php') {
if (!is_file($cache_file)) {
$cached_list = array();
foreach ($file_list as $key => $file) {
if (is_file($file)) {
$cached_list[$key] = include $file;
$cached_list[$key.'_mtime'] = filemtime($file);
}
}
file_put_contents($cache_file, "<?php\n\nreturn " . var_export($cached_list, 1) . ";\n");
}
else {
$cached_list = include $cache_file;
$modify = false;
foreach ($file_list as $key => $file) {
if (is_file($file)) {
if (!isset($cached_list[$key.'_mtime']) || $cached_list[$key.'_mtime'] != filemtime($file)) {
$cached_list[$key] = include $file;
$cached_list[$key.'_mtime'] = filemtime($file);
if (!$modify) $modify = true;
}
}
}
if ($modify)
file_put_contents($cache_file, "<?php\n\nreturn " . var_export($cached_list, 1) . ";\n");
}
return $cached_list;
}
$config = cached_file_by_mtime(array(
'file1' => 'file1.php',
'file2' => 'file2.php',
'file3' => 'file3.php',
'file3' => 'file3.php',
'file4' => 'file4.php',
'file5' => 'file5.php',
'file6' => 'file6.php',
));
//for ($i = 0; $i < 10000; $i++) {
// if (is_file($file))
// include($file);
//}
echo round(microtime(true) - $start, 6) * 1000;
其他的代码,大家去下载吧,就不贴了。
服务器环境是PHP 5.3.4的,win7 64环境,有xcache。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。