Benefits of using short-circuit evaluation

后端 未结 15 1454
余生分开走
余生分开走 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:54

    Depending upon the context, it can also be called "Guarding".

    And I've seen it in just about every language I've worked in - which pushes close to a dozen.

    0 讨论(0)
  • 2020-12-05 16:55

    Short circuit evaluation is translated into branches in assembly language in the same way if statements are (branches are basically a goto), which means it is not going to be any slower than if statements.

    Branches don't typically stall the pipeline, but the processor will guess whether the branch is taken or not, and if the processor is wrong it will have to flush everything that has happened since it made the wrong guess from the pipeline.

    Short circuit evaluation is also the most common name for it, and is found in most languages in some form or another.

    0 讨论(0)
  • 2020-12-05 16:55

    A single thread is sequential so if you have two ifs the first will of course be evaluated before the second, so I can't see a difference on that. I use the conditional-AND operator (which is what && is called afaik) much more than nested ifs. If I want to check something that may take a while to evaluate, I do the simpler test first then the harder one after the conditional and.

    a = obj.somethingQuickToTest() && obj.somethingSlowToTest();

    doesn't seem to be any different than

    a = false;
    if(obj.somethingQuickToTest())
       a = obj.somethingSlowToTest();

    0 讨论(0)
提交回复
热议问题