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

标签 php performance io cat

我正在用 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 只是从内存中的文件中加载数据,而 readfilecat 也会将数据输出到屏幕上,所以它们只是执行更多的操作。

如果你想比较file_get_contents和其他的,在它之前添加echo

此外,您没有释放分配给 $foo 的内存。如果您像上次测试那样移动 file_get_contents,您可能会得到不同的结果。

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

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

关于PHP 性能 file_get_contents() 与 readfile() 和 cat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24590017/

相关文章:

java - 使用依赖注入(inject)时会对运行时性能产生影响吗?

php - 在 sql 比较查询之前将长字符串转换为短哈希 - 提高性能?

c# - C# 中 Regex.Match 的静态版本与实例版本

c# - 异常处理问题

c - 从文件系统读取数据 vs 将数据直接编译到程序中

javascript - PHP session 变量未解析,但 ISSET 表示它正在运行且位于 0

php - PHP/Ajax匿名函数,迭代会导致错误? +如何在使用Ajax时显示标准PHP错误

php - 站点地图文件可以是 php 吗?

file - 去。将 []byte 写入文件导致零字节文件

php - 如何使内部客户数据与公共(public)客户门户保持同步?