Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>(Disclaimer: the following deals with very low-level optimizations that are most often not necessary. If you keep reading, you waive your right to complain that computers are fast and there is never any reason to worry about this sort of thing.)</p> <p>One advantage of eliminating an <code>if</code> statement is that you avoid branch prediction penalties. </p> <p>Branch prediction penalties are generally only a problem when the branch is not easily predicted. A branch is easily predicted when it is almost always taken/not taken, or it follows a simple pattern. For example, the branch in a loop statement is taken every time except the last one, so it is easily predicted. However, if you have code like</p> <pre><code>a = random() % 10 if (a &lt; 5) print "Less" else print "Greater" </code></pre> <p>then this branch is not easily predicted, and will frequently incur the prediction penalty associated with clearing the cache and rolling back instructions that were executed in the wrong part of the branch.</p> <p>One way to avoid these kinds of penalties is to use the ternary (<code>?:</code>) operator. In simple cases, the compiler will generate conditional move instructions rather than branches.</p> <p>So</p> <pre><code>int a, b, low; if (a &lt; b) low = a; else low = b; </code></pre> <p>becomes</p> <pre><code>int a, b, low; low = (a &lt; b) ? a : b </code></pre> <p>and in the second case a branching instruction is not necessary. Additionally, it is much clearer and more readable than your bit-twiddling implementation.</p> <p>Of course, this is a micro-optimization which is unlikely to have significant impact on your code.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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