我正在用 PHP 文件读取函数做一些基准测试,只是为了了解我的整体知识。 因此,我测试了三种不同的方式来读取我认为非常快的文件的全部内容。
- file_get_contents() 以其非常高的性能而闻名
- 在将数据直接输出到
stdout
时,readfile() 被认为是 file_get_contents() 的一个很好的替代品
- exec('cat filename') 一个非常方便和快速的 UNIX 命令
这是我的基准测试代码,请注意,我为 readfile()
启用了 PHP 缓存系统,以避免直接输出会完全伪造结果。
<?php
/* Using a quick PNG file to benchmark with a big file */
/* file_get_contents() benchmark */
$start = microtime(true);
$foo = file_get_contents("bla.png");
$end = microtime(true) - $start;
echo "file_get_contents() time: " . $end . "s\n";
/* readfile() benchmark */
ob_start();
$start = microtime(true);
readfile('bla.png');
$end = microtime(true) - $start;
ob_end_clean();
echo "readfile() time: " . $end . "s\n";
/* exec('cat') benchmark */
$start = microtime(true);
$bar = exec('cat bla.png');
$end = microtime(true) - $start;
echo "exec('cat filename') time: " . $end . "s\n";
?>
我已多次运行此代码以确认显示的结果,并且每次我都有相同的订单。这是其中之一的示例:
$ php test.php
file_get_contents() time: 0.0006861686706543s
readfile() time: 0.00085091590881348s
exec('cat filename') time: 0.0048539638519287s
如您所见,file_get_contents()
先到,然后是 readfile()
,最后是 cat
至于 cat
,即使它是一个 UNIX
命令(如此之快和一切:))我知道调用一个单独的二进制文件可能会导致相对较高的结果。
但我有点难以理解的是,为什么 file_get_contents()
比 readfile()
快?毕竟这大约是慢 1.3 倍。
这两个函数都是内置的,因此得到了很好的优化,并且由于我启用了缓存,readfile() 不是“尝试”将数据输出到 stdout
但是就像 file_get_contents() 一样,它会将数据放入 RAM。
我在这里寻找技术上的低级解释,以了解 file_get_contents()
和 readfile()
的优缺点,除了一个被设计为直接写入标准输出,而另一个在 RAM 中分配内存。
提前致谢。
最佳答案
file_get_contents
只是从内存中的文件中加载数据,而 readfile
和 cat
也会将数据输出到屏幕上,所以它们只是执行更多的操作。
如果你想比较file_get_contents
和其他的,在它之前添加echo
此外,您没有释放分配给 $foo 的内存。如果您像上次测试那样移动 file_get_contents,您可能会得到不同的结果。
此外,您正在使用输出缓冲,这也会导致一些差异 - 只需尝试在输出缓冲代码中添加其余函数以消除任何差异。
当比较不同的功能时,其余代码应该相同,否则你会受到各种影响。
关于PHP 性能 file_get_contents() 与 readfile() 和 cat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24590017/