ingredient count (v3)

Revision 3 of this benchmark created by bergi on


Preparation HTML

<script src="//underscorejs.org/underscore-min.js"></script>

Setup

var products = [{
      name: "Sonoma",
      ingredients: ["artichoke", "sundried tomatoes", "mushrooms"],
      containsNuts: false
    }, {
      name: "Pizza Primavera",
      ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"],
      containsNuts: false
    }, {
      name: "South Of The Border",
      ingredients: ["black beans", "jalapenos", "mushrooms"],
      containsNuts: false
    }, {
      name: "Blue Moon",
      ingredients: ["blue cheese", "garlic", "walnuts"],
      containsNuts: true
    }, {
      name: "Taste Of Athens",
      ingredients: ["spinach", "kalamata olives", "sesame seeds"],
      containsNuts: true
    }];
    
    function ic(p,o,i,b,g) {
          i|=0;g|=0;
          if(!b&&p&&!p.ingredients)
            while((g=ic(p[g].ingredients,o,0,g+1))&&p[g]);
          else {
                o[p[i]]=(o[p[i]]|0)+1;
            return p[i+1]?ic(p,o,i+1,b):b;
          }
        }
    
    function ic2(ps) {
        return ps.reduce(function (r, p) {
            p.ingredients.forEach(function (i) {
                r[i] = (r[i] || 0) + 1;
            });
            return r;
        }, {});
    }
    
    function ic3(ps) {
        return ps.reduce(function(r, p) {
            return p.ingredients.reduce(function(r, i) {
                r[i] = (r[i] || 0) + 1;
                return r;
            });
        }, {});
    }
    
    function ic4(ps) {
        var ic = {};
        for (var i=0, pl=ps.length; i<pl; i++)
            for (var is=ps[i], j=0, il=is.length; j<il; j++)
                r[i] = (r[i]|0) + 1;
        return ic;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
underscore
var ingredientCount = {};
_.flatten(products.map(function(x) {
  return x.ingredients;
})).map(function(y) {
  return ingredientCount[y] = (ingredientCount[y] || 0) + 1;
});
ready
recursion
var ingredientCount = {};
ic(products, ingredientCount);
ready
reduce + foreach
var ingredientCount = ic2(products);
ready
reduce + reduce
var ingredientCount = ic3(products);
ready
plain loops
var ingredientCount = ic4(products);
ready

Revisions

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