Chain vs Pipe

JavaScript performance comparison

Test case created by Mario T. Lanza and last updated

Info

Provide pipe as an alternative to chain.

Pros:

  1. It's faster.
  2. It can be used to compose a function in chaining style.
  3. It accepts verbs (methods) that aren't built into underscore.
  4. It's implementation is smaller than chain's -- just 1 method.
  5. It's more succinct -- get more done with less effort.

Cons:

  1. Syntax is less familiar.

For what it's worth it employs pointfree style which is preferred for reasons of its own.

http://www.haskell.org/haskellwiki/Pointfree

Preparation code

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

function pipe(seed){
  var seeded = arguments.length > 0, composed = [];
  return function piping(verb){
    if (arguments.length === 0) {
      var fn = _.compose.apply(null, composed);
      return seeded ? fn(seed) : fn;
    }
    var args = _.rest(arguments);
    composed.unshift(function(obj){
      return verb.apply(null, [obj].concat(args));
    });        
    return piping;
  }
};
_.pipe = pipe;

var chainCounter = function(lyrics) {
  return _(lyrics).chain()
    .map(function(line) { return line.words.split(' '); })
    .flatten()
    .reduce(function(counts, word) {
      counts[word] = (counts[word] || 0) + 1;
      return counts;
    }, {})
    .value();
};

var pipeCounter = _.pipe()
  (_.map, function(line) { return line.words.split(' '); })
  (_.flatten)
  (_.reduce, function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
    }, {})
  ();

</script>
<script>
Benchmark.prototype.setup = function() {
    var lyrics = [{line: 1, words: "I'm a lumberjack and I'm okay"},
      {line: 2, words: "I sleep all night and I work all day"},
      {line: 3, words: "He's a lumberjack and he's okay"},
      {line: 4, words: "He sleeps all night and he works all day"}];
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Chain
chainCounter(lyrics)
pending…
Pipe
pipeCounter(lyrics)
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