title: Javascript for..in vs for loop performance
body: <p>I was clustering around 40000 points using kmean algorithm. In the first version of the program I wrote the euclidean distance function like this</p>
  
  <pre><code>var euclideanDistance = function( p1, p2 ) { // p1.length === p2.length == 3
      var sum = 0;
      for( var i in p1 ){
          sum += Math.pow( p1[i] - p2[i], 2 );
      }
      return Math.sqrt( sum );
  };
  </code></pre>
  
  <p>The overall program was quite slow taking on average 7sec to execute. After some profiling I rewrote the above function like this</p>
  
  <pre><code>var euclideanDistance = function( p1, p2 ) { // p1.length === p2.length == 3
      var sum = 0;
      for( var i = 0; i &lt; p1.length; i++ ) {
          sum += Math.pow( p1[i] - p2[i], 2 );
      }
      return Math.sqrt( sum );
  };
  </code></pre>
  
  <p>Now the programs on average take around 400ms. That's a huge time difference just because of the way I wrote the for loop. I normally don't use <code>for..in</code> loop for arrays but for some reason I used it while writing this function.</p>
  
  <p>Can someone explain why there is this huge difference in performance between these 2 styles?</p>