在ES6中,我们可以使用rest参数,有效地创建参数数组. TypeScript使用for循环将其转换为ES5.我想知道是否存在使用for循环方法比使用Array.prototype.slice更好的选择?也许存在slice选项无法涵盖的极端情况?@H_403_2@
@H_403_2@
// Written in TypeScript
/*
const namesJoinTS = function (firstName,...args) {
return [firstName,...args].join(' ');
}
const res = namesJoinTS('Dave','B','Smith');
console.log(res)
*/
// TypeScript above transpiles to this:
var namesJoinTS = function (firstName) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return [firstName].concat(args).join(' ');
};
var res = namesJoinTS('Dave','Smith');
console.log(res); //Dave B Smith
// Vanilla JS
var namesJoinJS = function (firstName) {
var args = [].slice.call(arguments,1);
return [firstName].concat(args).join(' ');
};
var res = namesJoinJS('Dave','Smith');
console.log(res); // //Dave B Smith
此外,JavaScript正在朝着一种可以更轻松地优化的语言的方向发展,诸如参数之类的旧功能被更严格的新功能(剩余属性)所替代,从而具有更高的性能.使用它们通过美观的代码实现良好的性能,参数是过去的错误.@H_403_2@
@H_403_2@
I was wondering is there any scenarios where using the for loop approach is a better option than using Array.prototype.slice?@H_403_2@
好吧,在较早的V8版本上速度更快,但仍然需要测试这种情况.如果您为项目编写代码,我将始终选择更优雅的解决方案,在99%的情况下,理论上可能会松散的毫秒数无关紧要.@H_403_2@
@H_403_2@
Maybe there are edge cases that the slice option does not cover?@H_403_2@
否(AFAIK).@H_403_2@
*您可能会问“为什么更快?”,那是因为:@H_403_2@
参数本身很难优化,因为@H_403_2@
1)可以重新分配(参数= 3)@H_403_2@
2)它必须是“实时的”,不断变化的参数将反映到参数中@H_403_2@
因此,只有直接访问它,才能对其进行优化,因为编译器随后可能会用变量引用替换类似数组的访问器:@H_403_2@
@H_403_2@
function slow(a) {
console.log(arguments[0]);
}
// can be turned into this by the engine:
function fast(a) {
console.log(a);
}
如果您内联循环并且如果参数数量更改,则回退到另一个版本(可能更慢),这也适用于循环:@H_403_2@
@H_403_2@
function slow() {
for(let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
slow(1,2,3);
slow(4,5,6);
slow("what?");
// can be optimized to:
function fast(a,b,c) {
console.log(a);
console.log(b);
console.log(c);
}
function fast2(a) {
console.log(a);
}
fast(1,3);
fast(4,6);
fast2("what?");
现在,如果您调用另一个函数并传递参数,则情况将变得非常复杂:@H_403_2@
@H_403_2@
var leaking;
function cantBeOptimized(a) {
leak(arguments); // uurgh
a = 1; // this has to be reflected to "leaking" ....
}
function leak(stuff) { leaking = stuff; }
cantBeOptimized(0);
console.log(leaking[0]); // has to be 1