【发布时间】:2010-10-22 00:43:13
【问题描述】:
我需要检查文件是否在指定位置 ($path.$file_name) 的 HDD 上。
is_file() 和 file_exists() 函数之间有什么区别,在 PHP 中哪个更好/更快?
【问题讨论】:
我需要检查文件是否在指定位置 ($path.$file_name) 的 HDD 上。
is_file() 和 file_exists() 函数之间有什么区别,在 PHP 中哪个更好/更快?
【问题讨论】:
如果给定的路径指向一个目录,is_file() 将返回false。如果给定的路径指向一个有效的文件或目录,file_exists() 将返回true。所以这完全取决于你的需求。如果您想特别了解它是否是一个文件,请使用is_file()。否则,请使用file_exists()。
【讨论】:
file_exists() 最好命名为path_exists()
is_file() 是最快的,但最近的基准测试显示file_exists() 对我来说稍微快一些。所以我猜这取决于服务器。
我的测试基准:
benchmark('is_file');
benchmark('file_exists');
benchmark('is_readable');
function benchmark($funcName) {
$numCycles = 10000;
$time_start = microtime(true);
for ($i = 0; $i < $numCycles; $i++) {
clearstatcache();
$funcName('path/to/file.php'); // or 'path/to/file.php' instead of __FILE__
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "$funcName x $numCycles $time seconds <br>\n";
}
编辑:@Tivie 感谢您的评论。将周期数从 1000 更改为 10k。结果是:
当文件存在时:
is_file x 10000 1.5651218891144 秒
file_exists x 10000 1.5016479492188 秒
is_readable x 10000 3.7882499694824 秒
当文件不存在时:
is_file x 10000 0.23920488357544 秒
file_exists x 10000 0.22103786468506 秒
is_readable x 10000 0.21929788589478 秒
编辑:移动 clearstatcache();循环内。谢谢 CJ 丹尼斯。
【讨论】:
is_file() 比file_exists() 快。如果您知道它是一个文件(而不是目录),请务必使用它。
is_dir() 比 file_exists() 快 20%(它没有,顺便说一句),如果你只是检查目录,那可能是一个重要的区别......
都没有。
如果文件可以读取,is_file() 返回 true。
如果文件是目录,file_exists() 可以返回 true。
请注意,在某些极端情况下,当 is_file() 由于权限或边缘情况文件系统问题而导致 is_file() 无法确定其是否为“常规文件”时,file_exists() 返回 true。
速度在这里无关紧要,因为它们不一样,它们会根据情况交换速度位置。
【讨论】:
is_file()在什么情况下返回true?
我知道这篇文章很旧,但这些函数之间的区别不仅在于它们的行为。 如果使用 is_file() 来检查大文件是否存在,超过 2 行。你会感到惊讶。 文件不存在。 :( 但是,如果您使用 file_exists() 检查,那就可以了。
【讨论】:
is_file 如果与反斜杠一起使用会更快:\is_file。在这种情况下,PHP 将提供 opcache 优化,file_exists 也不会。
【讨论】: