Benefits of using short-circuit evaluation

后端 未结 15 1514
余生分开走
余生分开走 2020-12-05 16:23
boolean a = false, b = true;
if ( a && b ) { ... };

In most languages, b will not get evaluated because a is fals

15条回答
  •  情歌与酒
    2020-12-05 16:34

    Regarding whether or not short-circuiting is efficient, pipelining is unlikely to have much of an impact on performance. In situations where it could have an impact, there's nothing to stop the compiler from testing multiple conditions in parallel so long as these tests doesn't have side-effects. Plus, modern CPUs have several mechanisms useful for improving the pipeline performance of branchy code.

    Nested ifs will have the same effect as short-circuiting &&.

    'Short-circuit evaluation' is the most common name for it, and your friend is wrong about it being uncommon; it's very common.

提交回复
热议问题