n0p*_*0pe -2 perl performance if-statement eval
我的问题专门针对Perl,但我希望对大多数语言都有所启发.
使用eval()函数和if()语句之间是否存在实际差异(性能方面和效率方面)?
eval(-e /path/to/file) or die "file doesn't exist";
if (! -e /path/to/file) { die "file doesn't exist"; }
Run Code Online (Sandbox Code Playgroud)
首先,不要像这样进行微观优化.编写最容易遵循的代码更为重要.牢记这一点将导致更少的错误,并且避免一个错误比保存大量纳秒更重要.
也就是说,您可以检查perl如何编译这样的事情:
$ perl -MO=Concise,-exec -e '-e "/path/to/file" or die "file doesn\x27t exist";'
1 <0> enter
2 <;> nextstate(main 1 -e:1) v:{
3 <$> const[PV "/path/to/file"] s
4 <1> ftis sK/1
5 <|> or(other->6) vK/1
6 <0> pushmark s
7 <$> const[PV "file doesn't exist"] s
8 <@> die[t2] vK/1
9 <@> leave[1 ref] vKP/REFC
-e syntax OK
$ perl -MO=Concise,-exec -e 'if ( ! -e "/path/to/file") { die "file doesn\x27t exist"; }'
1 <0> enter
2 <;> nextstate(main 3 -e:1) v:{
3 <$> const[PV "/path/to/file"] s
4 <1> ftis sK/1
5 <1> not sK/1
6 <|> and(other->7) vK/1
7 <0> enter v
8 <;> nextstate(main 1 -e:1) v:{
9 <0> pushmark s
a <$> const[PV "file doesn't exist"] s
b <@> die[t2] vK/1
c <@> leave vKP
d <@> leave[1 ref] vKP/REFC
-e syntax OK
Run Code Online (Sandbox Code Playgroud)
您可以在第二个中看到一些简单的额外操作,其中包括-e的结果,进入和离开{}块,以及将die作为单独的语句.这个单独的陈述可能有用; 如果你在调试器中单步执行代码,它会在死亡之前停止.
使用Perl 5.12+或使用旧版本的Perl unless代替if !以下内容not:
$ perl -MO=Concise,-exec -e 'unless (-e "/path/to/file") { die "file doesn\x27t exist"; }'
1 <0> enter
2 <;> nextstate(main 3 -e:1) v:{
3 <$> const[PV "/path/to/file"] s
4 <1> ftis sK/1
5 <|> or(other->6) vK/1
6 <0> enter v
7 <;> nextstate(main 1 -e:1) v:{
8 <0> pushmark s
9 <$> const[PV "file doesn't exist"] s
a <@> die[t2] vK/1
b <@> leave vKP
c <@> leave[1 ref] vKP/REFC
-e syntax OK
Run Code Online (Sandbox Code Playgroud)
使用语句修饰符产生与-e ... or die代码相同的结果:
$ perl -MO=Concise,-exec -e 'die "file doesn\x27t exist" unless -e "/path/to/file";'
1 <0> enter
2 <;> nextstate(main 1 -e:1) v:{
3 <$> const[PV "/path/to/file"] s
4 <1> ftis sK/1
5 <|> or(other->6) vK/1
6 <0> pushmark s
7 <$> const[PV "file doesn't exist"] s
8 <@> die[t2] vK/1
9 <@> leave[1 ref] vKP/REFC
-e syntax OK
Run Code Online (Sandbox Code Playgroud)