做的更快!
换句话说,如果您只使用文件名,请停止使用 pathinfo。
我的意思是,如果你有一个完整的 pathname, pathinfo 是有意义的,因为它比仅仅查找点更聪明:路径可以包含点,而文件名本身可能没有。所以在这种情况下,考虑像 , pathinfo 这样的输入字符串d:/some.thing/myfile
和其他配备齐全的方法是一个不错的选择。
但是如果你只有一个没有路径的文件名,那么让系统工作得比它需要的更多是毫无意义的。这可以为您提供 10 倍的速度提升。
这是一个快速的速度测试:
/* 387 ns */ function method1($s) {return preg_replace("/.*\./","",$s);} // edge case problem
/* 769 ns */ function method2($s) {preg_match("/\.([^\.]+)$/",$s,$a);return $a[1];}
/* 67 ns */ function method3($s) {$n = strrpos($s,"."); if($n===false) return "";return substr($s,$n+1);}
/* 175 ns */ function method4($s) {$a = explode(".",$s);$n = count($a); if($n==1) return "";return $a[$n-1];}
/* 731 ns */ function method5($s) {return pathinfo($s, PATHINFO_EXTENSION);}
/* 732 ns */ function method6($s) {return (new SplFileInfo($s))->getExtension();}
// All measured on Linux; it will be vastly different on Windows
Those nanosecond values will obviously differ on each system, but they give a clear picture about proportions. SplFileInfo
and pathinfo
are great fellas, but for this kind of job it's simply not worth it to wake them up. For the same reason, explode()
is considerably faster than regex. Very simple tools tend to beat more sophisticated ones.
Conclusion
This seems to be the Way of the Samurai:
function fileExtension($name) {
$n = strrpos($name, '.');
return ($n === false) ? '' : substr($name, $n+1);
}
Remember this is for simple filenames only. If you have paths involved, stick to pathinfo or deal with the dirname separately.