each vs for loop

JavaScript performance comparison

Test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="headers">
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
</div>
<script>
Benchmark.prototype.setup = function() {
    var headers = $('#headers > div');
    var maxLengths = [];
};
</script>

Preparation code output

A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
each
headers.each(function(i) {
  var width = $(this).width(); //.style.width;
  maxLengths[i] = isNaN(width) ? 0 : width;
});
pending…
for loop
for (var i = 0; i < headers.length; i++) {
  var width = $(headers[i]).width(); //.style.width;
  maxLengths[i] = isNaN(width) ? 0 : width;
}
pending…
map
$.map(headers, function(elem, index) {
   return $(elem).width();
});
pending…

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

Compare results of other browsers

0 comments

Add a comment