title: Is it better to avoid using the mod operator when possible?
body: <p>I assume that calculating the modulus of a number is a somewhat expensive operation, at least compared to simple arithmetic tests (such as seeing if a number exceeds the length of an array). If this is indeed the case, is it more efficient to replace, for example, the following code:</p>
  <pre><code>res = array[(i + 1) % len];
  </code></pre>
  <p>with the following? :</p>
  <pre><code>res = array[(i + 1 == len) ? 0 : i + 1];
  </code></pre>
  <p>The first one is easier on the eyes, but I wonder if the second might be more efficient. If so, might I expect an optimizing compiler to replace the first snippet with the second when a compiled language is used?</p>
  <p>Of course, this &quot;optimization&quot; (if it is indeed an optimization) doesn't work in all cases (in this case, it only works if <code>i+1</code> is never more than <code>len</code>).</p>