forEach vs loop for sparse arrays

JavaScript performance comparison

Revision 19 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = [];
    for(var i = 0; i < 1000; i++) arr[i]=i;
   
    //make it very sparse
    for(var i=0; i<1000; i+=40) {
      for(var j=0; j<39; j++) {
        delete arr[i+j];
      }
    }
   
    function callback(){}
};
</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
forEach
arr.forEach(function(){});
pending…
loop
for(var i = 0, l = arr.length; i < l; i++){if (arr[i]) {callback(arr[i]);}}
pending…
while
var j=arr.length;

while(--j>0){if (arr[j]) {callback(arr[j]);}}
pending…
for 2
var i = -1;
var len = arr.length
for (; ++i < len;) {
   if (arr[i]) {callback(arr[i]);}
}
pending…
for 3
for (var i = arr.length-1; i > -1; i--) {if (arr[i]) {callback(arr[i]);}}
pending…
for 4
for (i = arr.length - 1; i >= 0; i--) {
  if (arr[i]) {callback(arr[i]);}
}
pending…
while 2
var i = arr.length;
while(i--) {
  if (arr[i]) {callback(arr[i]);}
}
pending…
for loop, most common form
for (var i = 0; i < arr.length; i++) {
  if (arr[i]) {callback(arr[i]);}
}
pending…
foreach with one function
arr.forEach(callback);
pending…
for..in loop
for (var prop in arr) {
  callback(arr[prop]);
}
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