for loop vs. _.each vs. $.each

JavaScript performance comparison

Test case created by Jan

Info

Comparing different looping constructs using native JavaScript, Underscore, or jQuery.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>
<script>
  var data = _.range(10000);
</script>
<script>
Benchmark.prototype.setup = function() {
    var sum = 0;
    function func(value) {
      sum += value;
    }
};
</script>

Preparation code output

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
for (var i = 0, l = data.length; i < l; ++i) {
  func(data[i]);
}
pending…
for in
for (var i in data) {
  func(data[i]);
}
pending…
while
var l = data.length;
var i = 0;
while (i < l) {
  func(data[i]);
  i++;
}
pending…
Array.prototype.forEach
data.forEach(function(v) {
  func(v);
});
pending…
_.each
_.each(data, function(v) {
  func(v);
});
pending…
$.each
$.each(data, function(i, v) {
  func(v);
});
pending…
_.each with named function
function f(v) {
  func(v);
}

_.each(data, f);
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