Chain vs Pipe

Benchmark created by Mario T. Lanza on


Description

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 HTML

<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>

Setup

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"}];

Test runner

Ready to run.

Testing in
TestOps/sec
Chain
chainCounter(lyrics)
ready
Pipe
pipeCounter(lyrics)
ready

Revisions

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