有一个我经常使用的 php 5 库的文件缓存系统。 当发出请求时,我会检查缓存文件,如果有,我会渲染它并退出。
$contents = file_get_contents( self::_cacheFile() );
echo $contents;
exit();
我必须执行 file_get_contents 而不是仅仅包含,因为缓存的 xml 文件很烦人
`<?xml version="1.0"?>`
有没有更好的方法在不触发短标签的情况下提取我的缓存文件?
最佳答案
因为 include
将评估文件的内容,例如通过 PHP 解释器运行并使用 include_path 查找文件,我会说 include
速度较慢。 file_get_contents
只会将文件的内容视为字符串。更少的开销,更快的速度。
来自 manual page :
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
但是,如果您是在输出文件之后,而不是将其放入字符串中,readfile()
甚至比 file_get_contents
快一点点。鉴于 include
'ing 也将输出任何非 PHP 内容,我猜这很可能是您想要的。
在我的台式机上修改了基准测试:
$start1 = microtime(1);
for($i=0; $i<100000; $i++) {
include 'log.txt';
}
$end1 = microtime(1) - $start1;
和
$start2 = microtime(1);
for($i=0; $i<100000; $i++) {
echo file_get_contents('log.txt');
}
$end2 = microtime(1) - $start2;
和
$start3 = microtime(1);
for($i=0; $i<100000; $i++) {
readfile('log.txt');
}
$end3 = microtime(1) - $start3;
结果
echo PHP_EOL, $end1, // 137.577358961
PHP_EOL, $end2, // 136.229552984
PHP_EOL, $end3; // 136.849179029
关于php - 如何读取缓存的xml文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328301/