title: Why are Scala for loops so much faster than while loops for processing a sequence of distinct objects?
body: <p>I recently read a post about for loops over a range of integers being slower than the corresponding while loops, which is true, but wanted to see if the same held up for iterating over existing sequences and was surprised to find the complete opposite by a large margin.</p>
  
  <p>First and foremost, I'm using the following function for timing:</p>
  
  <pre><code>def time[A](f: =&gt; A) = {
      val s = System.nanoTime
      val ret = f
      println("time: " + (System.nanoTime - s) / 1e6 + "ms")
      ret
  }
  </code></pre>
  
  <p>and I'm using a simple sequence of Integers:</p>
  
  <pre><code>val seq = List.range(0, 10000)
  </code></pre>
  
  <p>(I also tried creating this sequence a few other ways in case the way this sequence was accessed affected the run time. Using the <code>Range</code> type certainly did. This should ensure that each item in the sequence is an independent object.)</p>
  
  <p>I ran the following:</p>
  
  <pre><code>time {
    for(item &lt;- seq) {
      println(item)
    }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>time {
    var i = 0
    while(i &lt; seq.size) {
      println(seq(i))
      i += 1
    }
  }
  </code></pre>
  
  <p>I printed the results so to ensure that we're actually accessing the values in both loops. The first code snippet runs in an average of <strong>33 ms</strong> on my machine. The second takes an average of <strong>305 ms</strong>.</p>
  
  <p>I tried adding the mutable variable <code>i</code> to the for loop, but it only adds a few milliseconds. The <code>map</code> function gets similar performance to a for loop, as expected. For whatever reason, this doesn't seem to occur if I use an array (converting the above defined <code>seq</code> with <code>seq.toArray</code>). In such a case, the for loop takes 90 ms and the while loop takes 40 ms.</p>
  
  <p>What is the reason for this major performance difference?</p>