for, forEach, for of

JavaScript performance comparison

Test case created by mmis1000

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var arr = []
  var total = 5000
  
  for (var i = 0; i < total; i++) {
    arr.push(Math.random())
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
for
var result = 0

for (var i = 0; i < arr.length; i++) {
  var v = arr[i]
  result += (i + v)
}

window.result = result
pending…
forEach
var result = 0

arr.forEach((v, i) => {
  result += (i + v)
})

window.result = result
pending…
for of entries
var result = 0

for (var [i, v] of arr.entries()) {
  result += (i + v)
}

window.result = result
pending…
recursive w index
var result = 0

function scan(arr, i = 0) {
  if (i < arr.length) {
    var v = arr[i]
    return (i + v) + scan(arr, i + 1)
  } else {
    return 0
  }
}

window.result = scan(arr)
pending…
recursive w slice
// seriously?

var result = 0

function scan(arr, i) {
  var v = arr[0]

  if (arr.length === 1) {
    return (i + v)
  } else {
    return (i + v) + scan(arr.slice(1), i + 1)
  }
}

window.result = scan(arr)
pending…
for in
var result = 0

for (var i in arr) {
  var v = arr[i]
  result += (Number(i) + v)
}

window.result = result
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments