Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Efficiency depends, the logical or operator <code>||</code> is a short circuit operator meaning if <code>x</code> in your example is true it will not evaluate <code>y</code> or <code>z</code>. If it was a logical and <code>&amp;&amp;</code> then if <code>x</code> is false, it will not test <code>y</code> or <code>z</code>. Its important to note that this operation does not exist as an instruction so that means you have to use test and jump instructions. This means branching, which slows down things. Since modern CPU's are pipelined. </p> <p>But the real answer is it depends, like many other questions of this nature, as sometimes the benefit of short circuiting operations outweighs the cost.</p> <p>In the following extremely simple example you can see that bitwise or <code>|</code> is superior.</p> <pre><code>#include &lt;iostream&gt; bool test1(bool a, bool b, bool c) { return a | b | c; } bool test2(bool a, bool b, bool c) { return a || b || c; } int main() { bool a = true; bool b = false; bool c = true; test1(a,b,c); test2(a,b,c); return 0; } </code></pre> <p>The following is the intel-style assembly listings produced by gcc-4.8 with <code>-O3</code> :<br> <code>test1</code> assembly :</p> <pre><code>_Z5test1bbb: .LFB1264: .cfi_startproc mov eax, edx or eax, esi or eax, edi ret .cfi_endproc </code></pre> <p><code>test2</code> assembly :</p> <pre><code>_Z5test2bbb: .LFB1265: .cfi_startproc test dil, dil jne .L6 test sil, sil mov eax, edx jne .L6 rep; ret .p2align 4,,10 .p2align 3 .L6: mov eax, 1 ret .cfi_endproc </code></pre> <p>You can see that it has branch instructions, which mess up the pipeline.</p> <p>Sometimes however short-circuiting is worth it such as</p> <p><code>return x &amp;&amp; deep_recursion_function();</code></p> <p><strong>Disclaimer:</strong></p> <p>I would always use logical operators on <code>bools</code>. Unless performance really is critical, or maybe simple case like in <code>test1</code> and <code>test2</code> but with lots of bools. And in either case first verify that you do get an improvement.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload