多次刷新页面时读取文件变慢

Read file to slow when refreshing page multiple times

$myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("lastupdate.txt")); fclose($myfile);

这是我在 wordpress 插件中的 php 代码。当我更新网站 20 次时,加载单个页面大约需要 20 秒。没有这3行代码加载页面只需要1秒

你能告诉我为什么这么慢吗?

我想使用文本文件来存储一个字符串(2000 个字符)。 在我的测试中,里面只有一个 "hello world" ,它仍然需要一秒钟。我该如何解决这个问题?

非常感谢。

如果您只是想将文件内容转换为字符串,请使用 file_get_contents(),因为它具有更好的性能

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

在当前情况下,

<?php
  $myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!");
  echo fread($myfile,filesize("lastupdate.txt"));
  fclose($myfile);
?>

可以替换为readfile(),这样会读取文件并在一个命令中将其发送到浏览器

<?php
   readfile("lastupdate.txt");
?>

这与

基本相同
<?php
   echo file_get_contents("lastupdate.txt");
?>

除了 file_get_contents() 可能会导致大文件脚本崩溃,而 readfile() 不会。