title: Different ways to create Javascript arrays
body: <p>I want to understand the performance difference for constructing arrays. Running the following program, I am puzzled by the output below:</p>
  
  <pre><code>Time for range0: 521
  Time for range1: 149
  Time for range2: 1848
  Time for range3: 8411
  Time for range4: 3487
  </code></pre>
  
  <p>I don't understand why 3 takes longer than 4, while 1 takes shorter than 2. Also, seems the map function is very inefficient; what is the use of it?</p>
  
  <hr>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function range0(start, count) {
      var arr = [];
      for (var i = 0; i &lt; count; i++) {
          arr.push(start + i);
      }
      return arr;
  }
  
  function range1(start, count) {
      var arr = new Array(count);
      for (var i = 0; i &lt; count; i++) {
          arr[i] = start + i;
      }
      return arr;
  }
  
  function range2(start, count) {
      var arr = Array.apply(0, Array(count));
      for (var i = 0; i &lt; count; i++) {
          arr[i] = start + i;
      }
      return arr;
  }
  
  function range3(start, count) {
      var arr = new Array(count);
      return arr.map(function(element, index) {
          return index + start;
      });
  }
  
  function range4(start, count) {
      var arr = Array.apply(0, Array(count));
      return arr.map(function(element, index) {
          return index + start;
      });
  }
  
  function profile(range) {
      var iterations = 100000,
          start = 0, count = 1000,
          startTime, endTime, finalTime;
  
      startTime = performance.now();
  
      for (var i = 0; i &lt; iterations; ++i) {
          range(start, count);
      }
  
      endTime = performance.now();
  
      finalTime = (endTime - startTime);
      console.log(range.name + ': ' + finalTime + ' ms');
  }
  
  [range0, range1, range2, range3, range4].forEach(profile);</code></pre>
  </div>
  </div>
  </p>