Lazy cartesian product of arrays (arbitrary nested loops)

JavaScript performance comparison

Test case created by Rob W

Info

Stack Overflow question: Lazy cartesian product of arrays (arbitrary nested loops)

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var sets = [ [2,3,4,5], ['sweet','ugly'], ['cats','dogs','hogs'] ];
    function holla( n, adj, noun ){
      // console.log( [n,adj,noun].join(' ') );
      // Removed console.log, because that's not relevant
      //  for speed tests
    }
   
   
    function lazyProduct(arrays,callback,values){
      if (!values) values=[];
      var head = arrays[0], rest = arrays.slice(1), dive=rest.length>0;
      for (var i=0,len=head.length;i<len;++i){
        var moreValues = values.concat(head[i]);
        if (dive) lazyProduct(rest,callback,moreValues);
        else      callback.apply(this,moreValues);
      }
    }
    function LazyProduct(sets, holla) {
        var setLength = sets.length;
        function helper(array_current, set_index) {
            if (++set_index >= setLength) {
                holla.apply(null, array_current);
            } else {
                var array_next = sets[set_index];
                for (var i=0; i<array_next.length; i++) {
                    helper(array_current.concat(array_next[i]), set_index);
                }
            }
        }
        helper([], -1);
    }
   
};
</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
Phrogz
lazyProduct( sets, holla );
 
pending…
Rob W
LazyProduct( sets, holla );
 
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