I have a function f
that can be called with arbitrary arguments. When it is called with 2 arguments, it performs an operation. When it is called with >2 arguments, it must itself fold the others. That is, when we call f(a,b,c,d)
, the function should rearrange as f(f(f(a,b),c,d)
. I need this to be as optimized as possible. I come with 2 solutions and benchmarked them:
alphabet = 'abcdefhijklmnopqrstuvwxyz'.split('');
var last_mark;
benchmark = function(msg){
alert(msg.replace('$TIMEDIFF',Date.now()-last_mark));
last_mark=Date.now();
};
fa = function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){
if (c) return fa(fa(a,b),c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z);
return a+b;
};
fb = function(a,b,rest){
if (rest) return fb.apply(this,[fb(a,b)].concat(Array.prototype.slice.call(arguments,2)));
return a+b;
};
benchmark("Starting benchmark:");
for (var i=0; i<100000; ++i) fa.apply(this,alphabet);
benchmark("Function 1: $TIMEDIFF");
for (var i=0; i<100000; ++i) fb.apply(this,alphabet);
benchmark("Function 2: $TIMEDIFF");
The first solution was faster (200ms vs 4000ms on node.js). Can this be optimized even further?