What are the cases in which it is better to use unconditional AND (& instead of &&)

后端 未结 11 685
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 10:33

I\'d like to know some cases in Java (or more generally: in programming) when it is preferred in boolean expressions to use the unconditional AND (&

11条回答
  •  难免孤独
    2020-11-28 10:58

    If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.

    if(a && b) { }
    if(!(a || b)) { }
    

    is the same as

    if (a) if (b) { }
    if (!a) if (!b) { }
    

    which has two places a branch can occur.

    However using an unconditional & or |, there can be only one branch.

    Whetehr this helps or not is highly dependant on what the code is doing.

    If you use this, I sugegst commenting it to make it very clear why it has been done.

提交回复
热议问题