title: Two loops performance difference. Swapping inner and outer loop
body: <p>I had two loops (one nested in the other one) and I was wondering if there is any difference in how I nest these loops. Results of Code 1 and Code 2 are the same (100,000x4 = 4x100,000 = 400,000) but <a href="http://jsperf.com/llooptt1" rel="nofollow">jsPerf</a> shows that Code 2 is roughly 50% faster than Code 1.</p>
  
  <p>I'd like to kindly ask for your advice, I don't understand the difference between the two.</p>
  
  <p>Thank you very much.</p>
  
  <pre><code>var tt = function () {
        // do some stuff
        // for example:
        return (3);
      };
  </code></pre>
  
  <p>Test code 1:    </p>
  
  <pre><code>for (var i = 0; i &lt; 100000; i++) {
    for (var j = 0; j &lt; 4; j++) {
      tt();
    }
  }
  </code></pre>
  
  <p>Test code 2:</p>
  
  <pre><code>for (var j = 0; j &lt; 4; j++) {
    for (var i = 0; i &lt; 100000; i++) {
      tt();
    }
  }
  </code></pre>