eval() 与 if() ——有性能差异吗?
我的问题专门针对 Perl,但我希望对大多数语言有所启发。
使用 eval() 函数与 if() 语句之间是否存在实际差异(性能方面和效率方面)?
eval(-e /path/to/file) or die "file doesn't exist";
if (! -e /path/to/file) { die "file doesn't exist"; }
My question specifically is for Perl but I would like to be enlightened for most languages.
Is there an actual difference (performance-wise and efficiency-wise) between using an eval() function, versus an if() statement?
eval(-e /path/to/file) or die "file doesn't exist";
if (! -e /path/to/file) { die "file doesn't exist"; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,不要像这样进行微观优化。编写您最容易理解的代码更为重要。牢记这一点将减少错误,避免一个错误比节省大量纳秒更重要。
也就是说,您可以检查 perl 如何编译如下内容:
您可以看到第二个中涉及 -e 结果的逻辑非的一些琐碎的额外操作,进入和离开
{}
块,并将骰子作为单独的声明。这个单独的声明可能很有用;如果您在调试器中单步执行代码,它会在死亡之前停止。在旧版本的 Perl 中使用 Perl 5.12+ 或使用
unless
代替if !
会删除not
:使用语句修饰符会产生与以下相同的结果
-e ... or die
代码:First of all, don't micro-optimize like this. It is far more important to write code that you can most easily follow the sense of. Keeping this in mind will result in fewer bugs, and avoiding one bug is more important than saving a great number of nanoseconds.
That said, you can examine how perl compiles things like so:
You can see some trivial extra operations involved in the second for the logical not of the result of -e, entering and leaving the
{}
block, and for having the die as a separate statement. That separate statement can be useful; if you are stepping through the code in the debugger, it stops before dieing.Using Perl 5.12+ or using
unless
instead ofif !
in older version of Perl removes thenot
:Using a statement modifier produces the same results as the
-e ... or die
code:字符串
eval
(eval EXPR
)需要perl在每次执行时在运行时编译你的表达式,这比评估预编译的表达式要昂贵得多。对于任何提供类似运行时 eval 机制的语言(JavaScript、Ruby、Python?),在字符串eval
和块eval
中也是如此(
eval
>eval { BLOCK }),perl 设置一个错误处理程序,设置$@
并在出现 else 情况时返回到eval
语句的末尾致命错误。同样,这比在 Perl 和任何其他具有捕获异常功能的语言(Python、Java)中简单执行 BLOCK 的成本更高。The string
eval
(eval EXPR
) requires perl to compile your expression at runtime each time it is executed, which will be a lot more expensive than evaluating a pre-compiled expression. This is also true for any language that provides a similar run-time eval mechanism (JavaScript, Ruby, Python?)In both the string
eval
and the blockeval
(eval { BLOCK }
), perl sets up an error handler that sets$@
and returns to the end of theeval
statement in the event of an otherwise fatal error. Again, this is more expensive than simply executingBLOCK
, in Perl and in any other language with the facility to trap exceptions (Python, Java).