开发者社区> 问答> 正文

PHP单文件加载的性能的问题:报错

根据和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。

展开
收起
kun坤 2020-06-07 14:40:18 495 0
1 条回答
写回答
取消 提交回答
  • 2020-06-07 14:40:24
    赞同 展开评论 打赏
问答分类:
PHP
问答地址:
问答排行榜
最热
最新

相关电子书

更多
PHP 2017.北京 全球开发者大会——高可用的PHP 立即下载
PHP安全开发:从白帽角度做安全 立即下载
复杂PHP系统性能瓶颈排查及优化 立即下载