PHP性能文件\u get\u contents()与readfile()和cat
我正在做一些PHP文件读取函数的基准测试,只是为了我的总体知识。 所以我测试了三种不同的方法来读取文件的全部内容,我认为这会非常快PHP性能文件\u get\u contents()与readfile()和cat,php,performance,io,cat,Php,Performance,Io,Cat,我正在做一些PHP文件读取函数的基准测试,只是为了我的总体知识。 所以我测试了三种不同的方法来读取文件的全部内容,我认为这会非常快 file_get_contents()以其极高的性能而闻名 readfile()被认为是直接将数据输出到stdout exec('cat filename')一个非常方便快捷的UNIX命令 这是我的基准测试代码,请注意,我为readfile()启用了PHP缓存系统,以避免直接输出,从而完全伪造结果。 <?php /* Using a quick PNG f
- file_get_contents()以其极高的性能而闻名
- readfile()被认为是直接将数据输出到
stdout
- 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";
?>
如您所见,file\u get\u contents()
首先到达readfile()
,最后到达cat
至于cat
,即使它是一个UNIX
命令(速度如此之快,一切都如此:),我知道调用一个单独的二进制文件可能会导致相对较高的结果。
但我有点难以理解的是,为什么file\u get\u contents()
比readfile()快?毕竟,这大约要慢1.3倍
这两个函数都是内置的,因此经过了很好的优化。由于我启用了缓存,readfile()并没有“尝试”将数据输出到stdout
,而是像file_get_contents()一样将数据放入RAM中
我在这里寻找一个技术性的低级解释,以了解文件获取内容()
和读取文件()
的优缺点,另外一个是直接写入标准输出,而另一个是在RAM中分配内存
提前感谢。file\u get\u contents
仅从内存中的文件加载数据,而readfile
和cat
也会在屏幕上输出数据,因此它们只需执行更多操作
如果要将file\u get\u内容与其他内容进行比较,请在其前面添加echo
此外,您没有释放为$foo分配的内存。如果您将文件内容作为最后一个测试移动,则可能会得到不同的结果
此外,您正在使用输出缓冲,这也会导致一些差异——只需尝试在输出缓冲代码中添加其余函数,以消除任何差异
在比较不同的函数时,代码的其余部分应该是相同的,否则会受到各种影响。我更改了file\u get\u contents()和readfile()的顺序,但仍然得到相同的结果。但我想你的第一个假设是对的,因为这是我能理解的唯一解释。@Valentinmerier我将测试修改为:ob_start()$开始=微时间(真);echo file_get_内容(“$file”)$结束=微时间(真)-$start;ob_end_clean()代码>和文件内容变得和readfileWaow一样慢。这很有趣。这解释了很多
$ php test.php
file_get_contents() time: 0.0006861686706543s
readfile() time: 0.00085091590881348s
exec('cat filename') time: 0.0048539638519287s