Lodash _.forEach vs for in when iterating over objects

JavaScript performance comparison

Revision 9 of this test case created by Joshua Ball

Preparation code

<script src="https://raw.github.com/lodash/lodash/2.4.1/dist/lodash.js" type="text/javascript"></script>
<script>
Benchmark.prototype.setup = function() {
    var obj = {};
   
    for (var i = 0; i < 1000; ++i) {
      obj[i] = true;
    }
};
</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
var c = 0;
_.forEach(obj, function(val, key) {
  c = val;
});
pending…
for in
var c = 0;
for (i in obj) {
  c = obj[i];
};
pending…
_.forEach(_.keys());
var c = 0;
var keys = _.keys(obj);
_.forEach(keys, function(key) {
  c = obj[key];
});
pending…
for loop
var c = 0;
var keys = _.keys(obj);
for (var i = 0, len = keys.length; i < len; ++i) {
  c = obj[keys[i]];
};
pending…
for loop, all cached
var c = 0;
for (var i = 0, keys = _.keys(obj), len = keys.length; i < len; ++i) {
  c = obj[keys[i]];
};
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