function piping

JavaScript performance comparison

Test case created by axelarge

Preparation code

<script src="http://underscorejs.org/underscore-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var thingies = [],
        i = 1000;
    while (--i) {
      thingies.push({
        value: i.toString()
      });
    }
   
    function compose(f, g) {
      return function() {
        return g(f.apply(null, arguments));
      }
    }
   
    function compose1(f, g) {
      return function(x) {
        return g(f(x));
      }
    }
   
   
   
    function pipe() {
      return _.reduce(arguments, compose);
    }
   
    function pipe1() {
      return _.reduce(arguments, compose1);
    }
   
   
   
    function getter(prop) {
      return function(obj) {
        return obj[prop];
      }
    }
   
    function safeNumber(x) {
      return isNaN(x) ? 0 : x;
    }
   
    function plus1(x) {
      return x + 1;
    }
   
    function times2(x) {
      return x * 2;
    }
   
    _.mixin({
      sumBy: function(array, fn) {
        var sum = 0;
        _.each(array, function(element) {
          sum += fn(element);
        });
        return sum;
      }
    });
   
   
    var get = getter('value');
    var withVariadic = pipe(get, parseFloat, safeNumber, times2, plus1);
    var withOne = pipe1(get, parseFloat, safeNumber, times2, plus1);
    var withUnderscore = _.compose(plus1, times2, safeNumber, parseFloat, get);
};
</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
Variadic pipe
_.sumBy(thingies, withVariadic);
pending…
Single-argument pipe
_.sumBy(thingies, withOne);
pending…
With underscore's compose (iterative)
_.sumBy(thingies, withUnderscore);
pending…
Hand-rolled
_.sumBy(thingies, function(x) {
  return plus1(times2(safeNumber(parseFloat(get(x)))))
});
pending…
Inline ALL the things
_.sumBy(thingies, function(x) {
  var parsed = parseFloat(x.value);
  return (isNaN(parsed) ? 0 : parsed) * 2 + 1;
});
pending…

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

Compare results of other browsers

0 comments

Add a comment