lodash thisArg vs bind vs closure (v3)

Revision 3 of this benchmark created by Greg on


Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js" ></script>

Setup

var array = [];
    var obj = {}
    
    for (var i = 0; i < 10000; i++) {
      array[i] = i;
      obj[i] = i;
    }
    
    
    function foo(x) {
      return x * 2;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
bind
_.forEach(array, foo.bind(this));
ready
thisArg
_.forEach(array, foo, this);
ready
regular function
_.forEach(array, foo);
ready
closure
var self = this;
_.forEach(array, function(x) {
  return x * 2;
});
ready
for loop (non-optimized)
for (i = 0; i < array.length; i++) {
  foo(array[i]);
}
ready
for loop
i = 0;
len = array.length;
for (i; i < len; i++) {
  foo(array[i]);
}
ready
for loop, no fn call
i = 0;
len = array.length;
for (i; i < len; i++) {
  array[i] * 2;
}
ready
nop for loop
i = 0;
len = array.length;
for (i; i < len; i++) {}
ready
with has own check
for (i in array)
  if (array.hasOwnProperty(i)) {
    array[i] * 2;
  }
ready
has own check (obj)
for (i in obj)
  if (obj.hasOwnProperty(i)) {
    obj[i] * 2;
  }
ready
forEach on obj
_.forEach(obj, foo);
ready
has own check (obj) with fn
for (i in obj)
  if (obj.hasOwnProperty(i)) {
    foo(obj[i]);
  }
ready
has own check (obj) with fn no hasOwn
for (i in obj) {
  foo(obj[i]);
}
ready
using object.keys
i = 0;
keys = Object.keys(obj)
for(i; i < keys.length; i++) {
  foo(obj[keys[i]]);
}
ready
closure w/fn call
var self = this;
_.forEach(array, function(x) {
  foo(x);
});
ready

Revisions

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