短路和性能
大多数语言使用短路和/或运算符。例如
return foo() && bar();
,如果 foo() 返回 false,则永远不会调用 bar()。如果我们知道表达式的结果无论如何都会为 false,则无需调用 bar()。
据推测,这种行为最初是为了让代码运行得更快而实现的。然而,从那时起,技术已经发生了变化。特别是,与引入短路时的情况相比,分支相对于其他操作更加昂贵。
所以我想知道:对于短路操作员来说,这仍然是一种性能提升吗?
Most language use short-circuited and/or operators. For example
return foo() && bar();
will never call bar() if foo() returns false. There is no need to call bar() if we know that the result of the expression will be false anyways.
Presumably, this behavior was originally implemented in order to make code run faster. However, technology has changed since then. In particular branches are more expensive relative to other operations then would have been the case when short-circuiting was introduced.
So I'm wondering: is it still a performance gain to short circuit operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案应该是“也许”。
请查看 Eric Lippert 的此博客 C# 编译器完成的一些低级优化。
他认为,至少,短路简单布尔表达式的计算比仅计算整个事物的成本更高。以下是相关摘录:
The answer should be "maybe".
Take a look at this blog by Eric Lippert on some of the low level optimizations done by the C# compiler.
He argues that, at the very least, short circuiting the evaluation of a simple boolean expression is more expensive that just evaluating the entire thing. Here is the relevant excerpt:
是的。
想一想,如果你想做这样的事情怎么办:
第一个是简单的测试,另一个仍然需要几个月的时间来计算。
yes.
Think about it, what if you want to do something like this:
the first one is a simple test, the other will still take a few months to calculate.