forEach versus jQuery.each versus while loop (v5)

Revision 5 of this benchmark created by Mike McCaughan on


Preparation HTML

<div>
  <div class="a">
  </div>
  <div class="b">
    <div>
      <div>
      </div>
      <div>
      </div>
    </div>
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var x;
  var divs = Array.prototype.slice.call(document.getElementsByTagName('div'));
  var $divs = $('div');
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
While loop
var i = divs.length;
x = 0;
while (i--) {
divs[x].style.border = "1px solid Red";
  x++;
}
ready
Array forEach
x = 0;
divs.forEach(function(element) {
divs[x].style.border = "1px solid Red";
  x++;
});
ready
Array for..in
x = 0;
for (var i in divs) {
if (divs.hasOwnProperty(i)) {
divs[x].style.border = "1px solid Red";
  x++;
}
}
ready
jQuery.each
x = 0;
$(divs).each(function(index, element) {
element.style.border = "1px solid Red";
  x++;
});
ready
jQuery.each on cached selector
x = 0;
$divs.each(function(index, element) {
element.style.border = "1px solid Red";
  x++;
});
ready

Revisions

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

  • Revision 5: published by Mike McCaughan on