我只是在Chrome上运行了4个算法的基准测试:
就地:
// 1) splice method
{
let x = [8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44];
const y = [5, 6, 99, 5, 3, 4];
x.splice(0, 0, ...y); // 87'426 ops/s (but big variation of 35%)
// x is [5, 6, 99, 5, 3, 4, 8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44]
}
// 2) unshift method
{
let x = [8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44];
const y = [5, 6, 99, 5, 3, 4];
x.unshift(...y); // 69'471 ops/s
// x is [5, 6, 99, 5, 3, 4, 8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44]
}
复制:
// 3) spread operator
{
const x = [8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44];
const y = [5, 6, 99, 5, 3, 4];
const z = [...y, ...x]; // 17'118 ops/s
// z is [5, 6, 99, 5, 3, 4, 8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44]
}
// 4) concat method
{
const x = [8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44];
const y = [5, 6, 99, 5, 3, 4];
const z = y.concat(x); // 6'286 ops/s
// z is [5, 6, 99, 5, 3, 4, 8, 4, 1, 4, 124, 1, 14, 11, 9, 100, 6, 44]
}
总结:如果你想要在适当的位置预叠,unshift和splice都是很好的,如果你想要一个副本,那么展开运算符似乎是最好的选择…至少在Chrome上是这样。