短路和性能

发布于 2024-11-29 03:43:25 字数 283 浏览 1 评论 0原文

大多数语言使用短路和/或运算符。例如

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独陪着我 2024-12-06 03:43:25

答案应该是“也许”。

请查看 Eric Lippert 的此博客 C# 编译器完成的一些低级优化。

他认为,至少,短路简单布尔表达式的计算比仅计算整个事物的成本更高。以下是相关摘录:

简单说一下:不应该是 temp1.HasValue && temp2.​​HasValue?两个版本给出相同的结果;短路的效率更高吗?未必!将两个布尔值进行与运算的速度非常快,可能比执行额外的条件分支以避免极其快速的属性查找更快。而且代码肯定更小。 Roslyn 使用非短路 AND,我似乎记得早期的编译器也是这样做的。

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:

A brief aside: shouldn’t that be temp1.HasValue && temp2.HasValue? Both versions give the same result; is the short circuiting one more efficient? Not necessarily! AND-ing together two bools is extremely fast, possibly faster than doing an extra conditional branch to avoid what is going to be an extremely fast property lookup. And the code is certainly smaller. Roslyn uses non-short-circuiting AND, and I seem to recall that the earlier compilers do as well.

枫以 2024-12-06 03:43:25

是的。

想一想,如果你想做这样的事情怎么办:

return IsOKToStart() && CalculateFirstPrimeGreaterThanTrilion();

第一个是简单的测试,另一个仍然需要几个月的时间来计算。

yes.

Think about it, what if you want to do something like this:

return IsOKToStart() && CalculateFirstPrimeGreaterThanTrilion();

the first one is a simple test, the other will still take a few months to calculate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文