Benefits of using short-circuit evaluation

后端 未结 15 1498
余生分开走
余生分开走 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: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();

提交回复
热议问题