Run details:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
Chrome 84
Linux
Desktop
4 years ago
Test name Executions per second
For loop, basic 2134.0 Ops/sec
While loop, basic 2198.2 Ops/sec
For loop, cached (inside for statement) 2927.5 Ops/sec
For loop, cached (outside for statement) 3325.2 Ops/sec
For loop, i-- (caching inside for loop) 3298.9 Ops/sec
For loop, i-- (caching outside for loop) 3220.6 Ops/sec
While loop, cached 2067.5 Ops/sec
While loop, i-- 2114.1 Ops/sec
map 3484.8 Ops/sec
forEach 3860.6 Ops/sec
Script Preparation code:
x
 
  var arr = [];
  for (var i = 0; i < 1000; i++) {
    arr[i] = i;
  }
  function someFn(ix) {
    return ix * 5 + 1 / 3 * 8;
  }
Tests:
  • For loop, basic

     
    for (var i = 0; i < arr.length; i++) {
      someFn(arr[i]);
    }
  • While loop, basic

     
    var i = 0;
    while (i < arr.length) {
      someFn(arr[i]);
      i++;
    }
  • For loop, cached (inside for statement)

     
    for (var i = 0, len = arr.length; i < len; i++) {
      someFn(arr[i]);
    }
  • For loop, cached (outside for statement)

     
    var len = arr.length;
    for (var i = 0; i < len; i++) {
      someFn(arr[i]);
    }
  • For loop, i-- (caching inside for loop)

     
    for (var i = arr.length; i > 0; i--) {
      someFn(arr[i]);
    }
  • For loop, i-- (caching outside for loop)

     
    var i = arr.length;
    for (; i > 0; i--) {
      someFn(arr[i]);
    }
  • While loop, cached

     
    var len = arr.length;
    var i = 0;
    while(i < len){
      someFn(arr[i]);
      i++;
    }
  • While loop, i--

     
    var i = arr.length - 1;
    while(i > 0){
      someFn(arr[i]);
      i--;
    }
  • map

     
    arr.map(i => someFn(i))
  • forEach

     
    arr.forEach(i => someFn(i))