  
- 帖子
- 105
- 主题
- 98
- 精华
- 0
- 积分
- 263
- 贡献
- 105
- 激情
- 469
- 阅读权限
- 100
- 最后登录
- 2019-8-18
|
[应用&技术] 关于php函数 is_file和file_exists效率比较
目前在弄文件缓存的时候用到了判定文件存在与否,is_file()还是file_exists()呢?is_file和file_exists两者效率比较起来,谁的运行速度更快呢?还是做个测试吧:
* n/ f( \$ `& O6 |- <?php
- $start_time = get_microtime();
- for($i=0;$i<10000;$i++)//默认1万次,可手动修改
- {
- if(is_file('test.txt')) {
- //do nothing;
- }
- }
- echo 'is_file-->'.(get_microtime() - $start_time).'<br>';
- $start_time = get_microtime();
- for($i=0;$i<10000;$i++)//默认1万次,可手动修改
- {
- if(file_exists('test.txt')) {
- //do nothing;
- }
- }
- echo 'file_exits-->'.(get_microtime() - $start_time).'<br>';
- function get_microtime()//时间
- {
- list($usec, $sec) = explode(' ', microtime());
- return ((float)$usec + (float)$sec);
- }
- ?>
复制代码 # l% ]% h; E9 F: ?+ b2 a& b x
测试结果:
) j; H0 m. ]+ h6 O当文件存在时:& o0 Q9 E* a: p; d( `3 J. R3 {6 S) _
. d h6 p Y2 q" N( Y& Z" O0 t4 G
运行1万次:4 o, z3 W; n0 j" P
is_file–>0.00671219825744630 `7 A( d+ e; z5 Z( o; K) w' i9 p7 z
file_exits–>0.115324020385747 |1 D" m# p( x7 V+ z2 R3 Z
. L9 _( w4 I, Z0 s& D+ R- C运行10万次:% T0 [. q& p0 m* s/ Q
is_file–>0.0690560340881350 p3 C7 ^% i) @0 ]" _) ?
file_exits–>1.1521670818329
2 M6 }" T0 E5 H- o4 n5 g4 n! ]0 G- L5 }4 e3 z$ Q" |0 N
当运行100万次:- j" O0 [ Z# |9 e& R4 L0 G
is_file–>0.6924250125885- s' N2 K! T3 J2 `
file_exits–>11.497637987137' N' L z' F8 a( `# a& a
* f+ n7 [* k/ T0 [5 f: w+ _
* d7 B* r) c5 j; z, z& Z% D# I
当文件不存在时:; T1 q) M. Q( S8 e$ |( f5 ~* k
3 j- b. R: R! j- G1 O5 d9 ]
运行1万次:7 E9 n; b# R. R
is_file–>0.72184419631958
6 w S$ T/ u+ rfile_exits–>0.71474003791809
7 d) s) } h- ^% g$ S" i8 A8 ~; n
: r7 Q; }5 @. u& o* @4 M运行10万次:
+ X& X. h7 \1 j1 y# [: `6 Bis_file–>7.1535291671753 N3 z3 y' r& c6 v, m
file_exits–>7.0911409854889
! {7 `1 l4 ?6 G) s3 V2 L6 _/ U0 X. n
当运行100万次:: V4 [3 s; j3 H
is_file–>72.042867183685
* \$ W' \' z' |( `8 i' B! @file_exits–>71.789203166962* m8 o: d9 D( w+ {+ y1 v
- C: J/ C1 m! q# t+ q+ g2 A) j V超过1分钟了,别忘了在php第一行加句:+ a- l U* f. @" c' ]
set_time_limit(120);//时间限制120秒
) K+ @* r" t, s! n9 y结论:: J& o; @4 U. R2 F/ L [8 X( r
is_file()和file_exists()效率比较,结果当文件存在时,is_file函数比file_exists函数速度快14倍,当文件不存在时,两者速度相当。同理,当文件目录存在时,is_dir()比file_exists()快18倍。不存在时两者效率相当。PHP的file_exists = is_dir + is_file。1 y) ?3 {5 C x- @; o0 ?: b; T
* 如果要判断目录是否存在,请优先考虑函数 is_dir(directory)8 C$ Q; h4 \* V, Q- i
* 如果要判断文件是否存在,请优先考虑函数 is_file(filepath)
. M" Z2 Y% m6 X; o' `9 G& }, y$ jis_dir()对比file_exists()测试结果:
+ F5 Q$ }+ N- D/ G' P+ L, Y, P# t8 l9 ^ ?) l. F+ z1 `% \
当目录存在时,运行1万次* ~ V& ]: A+ x! `! M. A
is_dir–>0.0058560371398926
$ l J+ N: S# @file_exits–>0.11063098907471
/ V/ m. l# d, [( d/ {
' A) a$ i) Q D2 [* A. o' q当目录不存在时,运行1万次: \/ \% W8 ]7 `6 h# y, ?+ H
is_dir–>0.71594810485846 m, E8 R1 s2 {2 l2 o
file_exits–>0.71305584907532
$ _3 W" V! Y9 b0 C
. Y Y# _7 v( ?8 `参考:网络 |
|