I have a function f that can be called with arbitrary arguments. When it is called with two arguments, it performs the operation. When it is called by s> 2 arguments, it must dump the rest. That is, when we call f(a,b,c,d) , the function should be rebuilt as f(f(f(a,b),c,d) . I need this to be as optimized as possible. I supply 2 solutions and compare 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 (200 ms versus 4000 ms on node.js). Could this be optimized even further?