【问题标题】:PHP performance file_get_contents() vs readfile() and catPHP 性能 file_get_contents() 与 readfile() 和 cat
【发布时间】:2014-07-05 19:47:39
【问题描述】:

我正在对 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() 不是 "trying" 将数据输出到stdout,而是像 file_get_contents()它会将数据放入 RAM 中。

我在这里寻找一个技术性的低级解释,以了解 file_get_contents()readfile() 的优缺点,除了一个被设计为直接写入标准输出而另一个在 RAM 内分配内存的事实.

提前致谢。

【问题讨论】:

    标签: php performance io cat


    【解决方案1】:

    file_get_contents只是将文件中的数据加载到内存中,而readfilecat都将数据输出到屏幕上,所以它们只是执行了更多的操作。

    如果您想将file_get_contents 与其他人进行比较,请在其前面添加echo

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

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

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

    【讨论】:

    • 我更改了 file_get_contents() 和 readfile() 的顺序,但仍然得到相同的结果。但我猜你的第一个假设是对的,因为这是我能理解的唯一解释。
    • @ValentinMercier 我已将测试修改为:ob_start(); $start = microtime(true); echo file_get_contents("$file"); $end = microtime(true) - $start; ob_end_clean(); 并且 file_get_contents 变得与 readfile 一样慢
    • 哇,这很有趣。这解释了很多
    猜你喜欢
    • 2016-11-26
    • 2018-12-05
    • 1970-01-01
    • 2011-08-18
    • 2012-10-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多