为什么 PHP 缓存 filesize() 调用?

Why does PHP cache filesize() calls?

我刚刚花了几个小时为我的代码中的一个奇怪错误发疯。我正在使用 Twitter Streaming API 制作一个 PHP 应用程序,将新推文写入文件末尾。有时,包含推文的文件似乎毫无理由地被覆盖。

最后我发现这个埋在 filesize() page in the php docs:

Note: The results of this function are cached. See clearstatcache() for more details.

事实证明 PHP 正在缓存我对存储推文的文件的 filesize() 调用的结果。然后当我再次调用 filesize() 时,它实际上返回了一个完全错误的值。 (文件的旧长度,来自上一次函数调用)。

然后在 docs page for clearstatcache() 中,我发现了这个:

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance

再往下一点:

Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

为什么PHP会缓存这样的结果?为什么文件改变时缓存不会失效?更快的性能固然很好,但肯定不会以牺牲有效结果为代价。

正如您已经提到的,结果被缓存以提高性能。与文件系统交互比大多数其他操作更昂贵。

当文件系统发生变化时缓存没有失效的原因是因为监控会更加昂贵。这会否定缓存结果的价值。

至于为什么这样做是以在某些情况下产生意外结果为代价的:这只是一种权衡。如果不是以这种方式完成,我认为询问为什么不缓存结果将是一个同样有效的问题。无论哪种方式,都由您来缓存结果,或者刷新内置缓存。