什么's是调用具有可变参数的函数的有效方法
What's an efficient way to call a function with variable arguments?
我正在开发一个Javascript模块,它接受一个函数,并在稍后允许您调用它,这与currying没有什么不同。我注意到NodeJS从总是使用.apply()
切换到使用switch
语句,如下所示。
function applyFn(fn, args, ctx) {
switch (args.length) {
case 0: return fn.call(ctx); break;
case 1: return fn.call(ctx, args[0]); break;
case 2: return fn.call(ctx, args[0], args[1]); break;
case 3: return fn.call(ctx, args[0], args[1], args[2]); break;
default: return fn.apply(ctx, args);
}
}
上面的例子比下面的这个版本好吗?
function applyFn(fn, args, ctx) {
if (4 in args) return fn.apply(ctx, args);
if (3 in args) return fn.call(ctx, args[0], args[1], args[2], args[3]);
if (2 in args) return fn.call(ctx, args[0], args[1], args[2]);
if (1 in args) return fn.call(ctx, args[0], args[1]);
if (0 in args) return fn.call(ctx, args[0]);
return fn.call(ctx); // ಠ_ಠ
}
哪个版本的性能更好?
编辑:以下是我的使用方法:named-parameters.js
我意识到这是一种微观优化,但由于我的模块做了一件事,我想确保它做得很好。
我在这里制作了一个测试:http://jsperf.com/switch-vs-case-function-call
switch
看起来无疑是4和1 arg调用的赢家。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- Lodash _.debounce 具有唯一参数变体的单独队列
- 当使用多个值调用时,某些 mixin 参数保持不变
- 多次定义参数时获取 URL 参数值
- 通过 Ajax 获取 PHP 变量值,变量名称作为参数
- JavaScript无法从给定的参数中获取正确的变量值
- 没有参数的jQuery outerHeight()函数返回对象而不是参数值
- 将变量值传递给锚标记中的 href 参数
- 将参数附加到URL地址在多个函数中不起作用(第二个函数不变)
- 如何在不调用函数的情况下向函数实参添加参数
- 根据已有参数值向json中添加参数
- 当不指定url参数时,设置默认url参数值
- 试图保持输入参数不变
- 如何将范围变量值作为 FormName 传递给 ng-click 参数并获取 FormName.$valid 和 For
- 在DistanceMatrixStatus中传递参数回调或设置变量值