underscore vs manual (v10)

Revision 10 of this benchmark created on


Preparation HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js">

</script>

<script>
  var theArrays = [];
  (function() {
   var counter, entry;
  
   for (counter = 100; counter > 0; --counter) {
    entry = [
     {
      x: 1,
      y: counter
     },
     {
      x: 2,
      y: counter * 2
     },
     {
      x: 3,
      y: counter * 3
     }
    ];
    theArrays.push(entry);
   }
  })();
  
  function sumYValues(arrays) {
      var outer, inner, ar, entry, sum, result, x;
  
      sum = {};
      for (outer = 0; outer < arrays.length; ++outer) {
          ar = arrays[outer];
          for (inner = 0; inner < ar.length; ++inner) {
              entry = ar[inner];
              sum[entry.x] = (sum[entry.x] || 0) + entry.y;
          }
      }
  
      result = [];
      for (x in sum) {
          result.push({x: x, y: sum[x]});
      }
  
      return result;
  }
  
  function mixed(arr) {
    var i, ii = arr[0].length;
    return arr.reduce(function(prev, curr) {
      for (i = 0; i < ii; i++) {
        prev[i].y += curr[i].y;
      }
      return prev; 
    });
  }
  
  function optimisedNative(arr) {
    return arr.reduce(function(prev, curr) {
      return prev.map(function(val, key) {
        val.y += curr[key].y;
        return val;
      });
    });
  }
  
  function createOutput(arr) {
          return arr.reduce(function (prev, curr) {
              return prev.map(function(val, index) {
                  return {
                      x: val.x,
                      y: val.y + curr[index].y
                  }
              });
          });
      }
  
  function createOutput2(arrays) {
        return _.reduce(arrays, function(memo, arr) {
            return _.map(memo, function(val, index) {
                return {
                    x: val.x,
                    y: val.y + arr[index].y
                };
            });
        });
    }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Loops
sumYValues(theArrays);
ready
Native
createOutput(theArrays);
ready
underscore
createOutput2(theArrays);
ready
Mixed
mixed(theArrays);
ready
optimised native
optimisedNative(theArrays);
ready

Revisions

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