underscore each vs map (v2)

Revision 2 of this benchmark created by Henry on


Description

compare _.each with _.map with native while

Preparation HTML

<script src="http://underscorejs.org/underscore.js"></script>

Setup

var a = [];
    var strings = ['dogs', 'cats', 'mice', 'ohmy', 'cowardice'];
    var s;
    _.times(50, function(n) {
      s = strings[Math.floor(n / 10)] + ":" + strings[n % 5] + ":" + Math.floor((n % 10) / 5);
      a.push({
        num: n,
        string: s
      });
    });
    
    function getNum(e) {
      var split = e.string.split(":");
      var tens = split[0],
        ones = split[1],
        high = split[2];
      return strings.indexOf(tens) * 10 + strings.indexOf(ones) + 5 * high;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
_.each
var b = [];
_.each(a, function(e) {
  b.push(getNum(e));
});
ready
_.map
var b = _.map(a, getNum);
ready
native for loop
var b = [];
for (var i = 0; i < a.length; i++) {
  b.push(getNum(a[i]));
}
ready
native map
var b = a.map(getNum);
ready
native for, cached
var b = [];
for (var i = 0, len = a.length; i < len; i++) {
  b.push(getNum(a[i]));
}
ready
native for, cached
var b = [];
for (var i = 0, len = a.length; i < len; i++) {
  b.push(getNum(a[i]));
}
ready
native while
var b = [];
var length = a.length;
var i = 0;
while (i < length) {
  b.push(getNum(a[i++]));
}
ready

Revisions

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