file_get_contents比包含更慢吗?

时间:2010-02-24 18:04:34

标签: php xml caching

我经常使用的php 5库有一个文件缓存系统。 当我发出请求时,我会检查一个缓存的文件,如果有一个我渲染它并退出。

$contents = file_get_contents( self::_cacheFile() );
echo $contents;
exit();     

我必须执行file_get_contents而不是仅包含因为缓存的xml文件与烦人的

`<?xml version="1.0"?>` 

有没有更好的方法可以在没有短标签触发的情况下拉入我的缓存文件?

6 个答案:

答案 0 :(得分:35)

由于include会评估文件的内容,例如通过PHP解释器运行并使用include_path查找文件,我会说include更慢。 file_get_contents只会将文件内容视为字符串。开销更少,速度更快。

来自manual page

  

file_get_contents()是将文件内容读入字符串的首选方法。如果您的操作系统支持,它将使用内存映射技术来提高性能。

但是,如果您在输出文件后,而不是将其变为字符串,readfile()甚至比file_get_contents快一点。鉴于include'ing将输出任何非PHP内容,这可能更有可能是我想的。

在我的桌面计算机上修改了基准:

$start1 = microtime(1);
for($i=0; $i<100000; $i++) {
    include 'log.txt';
}
$end1 = microtime(1) - $start1;

$start2 = microtime(1);
for($i=0; $i<100000; $i++) {
    echo file_get_contents('log.txt');
}
$end2 = microtime(1) - $start2;

$start3 = microtime(1);
for($i=0; $i<100000; $i++) {
    readfile('log.txt');
}
$end3 = microtime(1) - $start3;

结果

echo PHP_EOL, $end1, // 137.577358961
     PHP_EOL, $end2, // 136.229552984
     PHP_EOL, $end3; // 136.849179029

答案 1 :(得分:11)

file_get_contentsinclude不会做同样的事情:

  • file_get_contents读取文件的内容,并将其作为字符串
  • 返回
  • include将执行文件的内容。

关于速度,没有操作码缓存,我认为file_get_contents理论上应该更快,因为它更少计算(没有编译/执行代码)

尽管如此,最重要的可能是你要做的事情:如果你只想阅读文件,你应该使用file_get_contents

答案 2 :(得分:11)

没有什么比一个(做得好的)基准(比它看起来更难,我可能忽略了一些东西)。尽管两者都是在相同条件下制造的,但它们应该作为测量棒。

test.txt是一个12kB,876行的文本文件:

vinko@parrot:~$ ls -la test.txt ; wc -l test.txt
-rw-r--r-- 1 vinko vinko 12264 2010-02-24 19:08 test.txt
876 test.txt

file_get_contents.php:

vinko@parrot:~$ more file_get_contents.php
<?php
echo file_get_contents("test.txt");
?>

include.php

vinko@parrot:~$ more include.php
<?php
include("test.txt");
?>

readfile.php

vinko@parrot:~$ more readfile.php
<?php
readfile("test.txt");
?>

因此,我们计算每次执行1万次迭代的时间:

vinko@parrot:~$ time for i in `seq 10000`; do php file_get_contents.php >/dev/null; done

real    3m57.895s
user    2m35.380s
sys     1m15.080s

vinko@parrot:~$ time for i in `seq 10000`; do php include.php >/dev/null; done

real    3m57.919s
user    2m37.040s
sys     1m16.780s

vinko@parrot:~$ time for i in `seq 10000`; do php readfile.php >/dev/null; done 
real    3m57.620s
user    2m38.400s
sys     1m14.100s

结论:对于使用Suhosin Patch的PHP 5.2.4上的12 kB文本文件,这三个实际上都是等效的。

答案 3 :(得分:11)

如果你要做的只是输出文件内容,你应该使用readfile()。这比file_get_contents()

更快,内存更少

答案 4 :(得分:6)

感谢小费,对于那些好奇的人

readfile();
<!-- dynamic page rendered in 0.133193016052 seconds.-->
<!-- static page rendered in 0.00292587280273 seconds.-->

VS

file_get_contents();
<!-- dynamic page rendered in 0.133193016052 seconds.-->
<!-- static page rendered in 0.00303602218628 seconds.-->

VS

include();
<!-- dynamic page rendered in 0.133193016052 seconds.-->
<!-- static page rendered in 0.00348496437073 seconds.-->

答案 5 :(得分:1)

file_get_contents是检索缓存文件的最快方法,原因如下:

  1. 它不会对它加载的数据执行任何处理(解析PHP代码,处理换行符等)。
  2. 它使用优化技术尽快加载文件(内存映射文件为一个)。
相关问题