for in vs for vs reduce vs foreach

JavaScript performance comparison

Revision 5 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = [1, 2, 3]
   
    Array.prototype.customForEach = function(fct) {
        for (var i = 0, l = this.length; i < l; i++) {
          fct(this[i])
        }
    }
   
    var elm = document.createElement("div");
    document.body.appendChild(elm);
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
for in
var sum = 0
for (var num in arr) {
  sum += num
}
pending…
forEach
var sum = 0
arr.forEach(function(num) {
  sum += num
})
pending…
for-loop
var sum = 0
for (var i = 0; i < arr.length; i++) {
  sum += arr[i]
}
pending…
reduce
arr.reduce(function(sum, num) {
  return sum + num
}, 0)
pending…
for-loop with var
var sum = 0
for (var i = 0; i < arr.length; i++) {
  var num = arr[i]
  sum += num
}
pending…
custom each loop
var sum = 0
arr.customForEach(function(num) {
  sum += num
})
pending…
write the result to the DOM
elm.innerHTML = "sum: "+6;
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. Here’s a list of current revisions for this page:

0 comments

Add a comment