我已经做了一个小的基准测试,但在查看结果之前,让我们看看这些函数是如何工作的。您可以在此处阅读PHP源代码。这里有一个法语版本的答案,本周早些时候撰写,时机不错。
我也会谈论is_file()
,因为它被定义为源代码中相同的核心函数。通过核心函数,我指的是C源代码,无法从PHP语言访问到您的脚本中。
据我所知,file_exists()
和 is_file()
是核心函数 php_stat()
的子函数。这是高度简化的伪代码流程:
function php_stat($file)
{
'file_exists'
↳ virtual_file_ex($file)
↳ virtual_access($file)
'Windows'
↳ tsrm_win32_access($file)
↳ return access($file)
'Other systems'
↳ return access($file)
'is_file'
↳ return $file.st_mode == S_IFREG
}
stream_resolve_include_path()
的伪代码:
function stream_resolve_include_path($file)
{
zend_resolve_path($file)
↳ php_resolve_path_for_zend($file)
↳ php_resolve_path($file)
↳ tsrm_realpath($file)
↳ return estrdup($file)
}
从这里开始,即使没有基准测试的数值结果,您也可以看出一个函数在资源上的消耗较大。
基准测试的代码:
function bench_file($file) {
$res = array();
$max = 1000000;
$res[] = microtime(1);
for ( $i = 0; $i < $max; ++$i ) {
if ( is_file($file) ) {
}
}
$res[] = microtime(1);
clearstatcache();
$res[] = microtime(1);
for ( $i = 0; $i < $max; ++$i ) {
if ( file_exists($file) ) {
}
}
$res[] = microtime(1);
clearstatcache();
$res[] = microtime(1);
for ( $i = 0; $i < $max; ++$i ) {
if ( stream_resolve_include_path($file) !== false ) {
}
}
$res[] = microtime(1);
printf(
'is_file = %f, file_exists = %f, stream_resolve_include_path = %f',
$res[1] - $res[0], $res[3] - $res[2], $res[5] - $res[4]
);
}
让我们测试一个已存在的文件(1)和一个不存在的文件(2):
1 : is_file = 0.218582, file_exists = 0.742195, stream_resolve_include_path = 1.626521
2 : is_file = 0.458983, file_exists = 0.644638, stream_resolve_include_path = 5.623289
结果说明一切 ;)
Benchmark v2 - 只是一个更简单的方法来添加新函数进行测试。
function micro($func, $file) {
$max = 1000000;
$start = microtime(1);
for ( $i = 0; $i < $max; ++$i ) {
if ( $func($file) ) {
}
}
$end = microtime(1);
clearstatcache();
return $end - $start;
}
function bench_file($file) {
$res = array(
'is_file' => micro('is_file', $file),
'file_exists' => micro('file_exists', $file),
'stream_resolve_include_path' => micro('stream_resolve_include_path', $file)
);
$ret = '';
foreach ( $res as $key => $value ) {
$ret .= sprintf('%s = %f, ', $key, $value);
}
return trim($ret, ', ');
}
echo '<pre>', bench_file('file-ok'), "\n", bench_file('file-ko'), '</pre>';
结果:
is_file = 0.295752, file_exists = 0.852082, stream_resolve_include_path = 1.759607
is_file = 0.527770, file_exists = 0.724793, stream_resolve_include_path = 5.916151
调用$funct()
的成本很小,这解释了稍高一些的数字。