jQuery each vs JS forEach

JavaScript performance comparison

Revision 28 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  // Setup collection
  var collection = [];
  var t = 0;
  for (var i = 0; i < 1000; i++) {
    collection.push('Index element ' + i);
  }

  var collection2 = [];
  for (var i = 0; i < 20; i++) {
    collection.push('New index element ' + i);
  }
</script>
    

Preparation code output

<script> // Setup collection var collection = []; var t = 0; for (var i = 0; i < 1000; i++) { collection.push('Index element ' + i); } var collection2 = []; for (var i = 0; i < 20; i++) { collection.push('New index element ' + i); } </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
jQuery
var temp = [];
$.each(collection2, function(index, element2) {
  $.each(collection, function(index, element1) {
    if (element1 === element2) {
      // do something 
      temp.push(element1);
    }
  });
});
pending…
JS forEach()
var temp = [];
var a = 0;
for (var idx2 = 0; idx2 < collection2.length; idx2++) {
  for (var idx1 = a; idx1 < collection.length; idx1++) {
    if (collection[idx1] === collection2[idx2]) {
      temp.push(collection[idx1]);
      a = idx1 + 1;
      // do something 
      break
    }
  }
  if (!a) {
    break
  }
}
pending…
JS for(var x in collection)
var temp = [];
var tmp1, tmp2;
for (var idx2 = 0; idx2 < collection2.length; idx2++) {
  tmp1 = collection2[idx2];
  for (var idx1 = 0; idx1 < collection.length; idx1++) {
    tmp2 = collection[idx1];
    if (tmp2 === tmp1) {
      temp.push(tmp1);
      // do something 
    }
  }
}
pending…
Js for
var temp = [];
var idx = 0;
for (var idx2 = 0; idx2 < collection2.length; idx2++) {
  for (var idx1 = 0; idx1 < collection.length; idx1++) {
    if (collection[idx1] === collection2[idx2]) {
      temp.push(collection[idx1]);
      // do something 
    }
  }
}
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