我有一个函数f
可以用任意参数调用。当它被2个参数调用时,它执行一个操作。当它被调用> 2个参数时,它必须本身折叠其他。也就是说,当我们调用f(a,b,c,d)
时,函数应重新排列为f(f(f(a,b),c,d)
。我需要这个尽可能优化。我带着2个解决方案和基准测试他们:折叠函数参数的最佳方式是什么?
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");
第一个解决方案是快(node.js的上200毫秒VS 4000ms)。这可以进一步优化吗?
大概是对http://codereview.stackexchange.com/更适合。 –
谢谢。有些有趣的堆栈交换我不知道。 – MaiaVictor
@Cam你是什么意思? – MaiaVictor