PHP 性能 file_get_contents() 与 readfile() 和 cat

Val*_*ier 5 php io performance cat

我正在对 PHP 文件读取函数进行一些基准测试,只是为了了解我的整体知识。因此,我测试了三种不同的方法来读取文件的全部内容,我认为这会非常快。

  • file_get_contents() 以其极高的性能而闻名
  • 当涉及到将数据直接输出到stdout
  • exec('cat filename') 一个非常方便且快速的 UNIX 命令

这是我的基准测试代码,请注意,我启用了 PHP 缓存系统,以readfile()避免完全伪造结果的直接输出。

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

我已经多次运行此代码以确认显示的结果,并且每次我都有相同的订单。以下是其中之一的示例:

$ php test.php
file_get_contents() time: 0.0006861686706543s
readfile() time: 0.00085091590881348s
exec('cat filename') time: 0.0048539638519287s
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,file_get_contents()首先出现,然后到达readfile(),最后cat

至于cat即使它是一个UNIX命令(如此快和一切:))我知道调用单独的二进制文件可能会导致相对较高的结果。但我有点难以理解的是,为什么file_get_contents()比 更快readfile()?毕竟慢了大约1.3 倍。

这两个函数都是内置的,因此得到了很好的优化,并且由于我启用了缓存,readfile() 并不是“尝试”将数据输出到stdout,而是像 file_get_contents() 一样,它将数据放入 RAM 中。

我在这里寻找技术性的低级解释,以了解其优缺点file_get_contents()readfile()此外,一个设计为直接写入标准输出,而另一个则在 RAM 内进行内存分配。

提前致谢。

Max*_*sky 7

file_get_contents只从内存中的文件中加载数据,而两者readfilecat将数据输出到屏幕上,因此它们只是执行更多操作。

如果要file_get_contents与其他比较,请echo在前面添加

另外,您没有释放为 $foo 分配的内存。如果您将 file_get_contents 作为上次测试移动,您可能会得到不同的结果。

此外,您正在使用输出缓冲,这也会导致一些差异 - 只需尝试在输出缓冲代码中添加其余函数即可消除任何差异。

当比较不同的函数时,其余的代码应该是相同的,否则你就会受到各种影响。