在PHP中哪个更快:
echo file_get_contents('http://example.com/file.txt');
或
$file = file_get_contents('http://example.com/file.txt'); echo $file;
我正在使用服务器端包含(require('/var/www/menu.php');)为我的菜单等,但想使用某些东西(例如在其他领域)
谢谢
发布于 2012-08-12 15:24:21
如果你在非常大的文件的everypage上大量使用这个方法,那么你会因为额外的变量而浪费内存空间。所以更好的方法是:
echo file_get_contents('http://example.com/file.txt');更好的问题是问哪个函数更快,file_get_contents()和fread()?然后答案是,如果文件大于1MB或2MB,那么使用file_get_contents(),它可以执行得更好。
你可以在这里看到一个基准:
File Read Type Average Execution Time Type of File
file_get_contents() 0.3730ms Small
fread() 0.1108ms Small
file_get_contents() 0.012ms Large
fread() 0.019ms Large 大文件为2.3MB,小文件为3.0KB。
我对小文件运行了这两个函数100,000次,对大文件只运行了一次。
发布于 2012-08-12 15:12:59
无论有什么不同,如果有的话,与首先发出HTTP请求来获取file.txt的内容相比,它是100%可以忽略的。写下你的意思。如果你不需要一个变量,就不要使用它。
发布于 2012-08-12 15:15:08
我做了一个小测试,但我不确定在你的情况下哪个更快。在我看来,microtime是测试spead的一个很好的工具。
<html>
<body>
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
echo "<textarea>".file_get_contents('http://in.gr')."</textarea>";
$time_end = microtime_float();
$time = $time_end - $time_start;
echo $time;
$time_start = microtime_float();
$file = file_get_contents('http://in.gr'); echo "<textarea>".$file."</textarea>";
$time_end = microtime_float();
$time = $time_end - $time_start;
echo $time;
?>
</body>
</html>https://stackoverflow.com/questions/11920374
复制相似问题