title: What effect will branch prediction have on the following C loop?
body: <p>My experience with C is relatively modest, and I lack good understanding of its compiled output on modern CPUs. The context: I'm working on image processing for an Android app. I have read that branch-free machine code is preferred for inner loops, so I'd like to know whether there could be a significant performance difference between something like this:</p>
  
  <pre><code>if (p)      { double for loop, computing f() }
  
  else if (q) { double for loop, computing g() }
  
  else        { double for loop, computing h() }
  </code></pre>
  
  <p>Versus the less verbose version which does the condition checking within the loop:</p>
  
  <pre><code>for (int i = 0; i &lt; xRes; i++)
  {
      for (int j = 0; j &lt; yRes; j++)
      {
          image[i][j] = p ? f() : (q ? g() : h());
      }
  }
  </code></pre>
  
  <p>In this code, p and q are expressions like <code>mode == 3</code>, where <code>mode</code> is passed into the function and never changed within it. I have three simple questions:</p>
  
  <p>(1) Would the first, more verbose version compile to more efficient code than the second version?</p>
  
  <p>(2) For the second version, would performance improve if I evaluate and store the results of <code>p</code> and <code>q</code> above the loop, so I can replace the boolean expressions in the loop with variables?</p>
  
  <p>(3) Should I even be worried about this, or will branch prediction (or some other optimization) ensure the boolean expressions in the loop(s) are almost never evaluated anyway?</p>
  
  <p>Finally, I'd be delighted if someone can say whether the answers to these 3 questions depend on the architecture. I'm interested in the main Android NDK platforms: ARM, MIPS, x86 etc. My thanks in advance!</p>