为什么Array.from的回调比map函数慢得多?

时间:2019-05-21 20:00:36

标签: javascript arrays loops map-function

今天进行一些性能测试时,我发现Array.from的回调工作比单独运行Array.map函数要慢得多。

以以下方式对长度为3200万个项目的阵列进行了测试。

let t1;
const arr = Array.from(new Array(32000000), (v,i) => {
    if (i === 0) t1 = performance.now();
    return i;
});
let t2 = performance.now();

t2 - t1; // ~4500ms


let arr2 = Array.from(new Array(32000000));
arr2 = arr2.map((v,i) => {
    if (i === 0) t1 = performance.now();
    return i;
});
t2 = performance.now();

t2 - t1; // ~500ms

我一直认为Array.from仅在创建数组时在其自身上运行map函数。 polyfills的代码看起来也一样。知道为什么性能会有如此差异吗?

在macOS的Google Chrome 74.0.3729.157中进行了测试

1 个答案:

答案 0 :(得分:1)

映射功能并不是很慢,Array.from本身

如果我们删除所有不必要的变量和条件语句,则会得到以下简化的基准,该基准返回:

Chrome 74:

Array.from with map: 4735.970ms
Array.map: 166.405ms
Array.map with from: 5101.585ms
Array.from: 4999.910ms

Firefox 67:


Array.from with map: 729.000ms
Array.map: 41.000ms
Array.map with from: 1150.000ms
Array.from: 619.000ms

因此,我们可以看到映射实际上几乎不需要时间,所有花费大量时间的是Array.from调用。

我认为Array.from的分配内存和创建新Array的速度比Array.map返回的数组慢得多,因为它比map函数更通用,更复杂。只需比较一下它们的规格:Array.prototype.mapArray.fromArray.from似乎很难为其优化编译器。

const arr = new Array(32000000);

console.time('Array.from with map');
const arr1 = Array.from(arr, (v,i) => {
    return i;
});
console.timeEnd('Array.from with map');


console.time('Array.map');
const arr2 = arr.map((v,i) => {
    return i;
});
console.timeEnd('Array.map');



console.time('Array.map with from');
const arr3 = Array.from(arr).map((v,i) => {
    return i;
});
console.timeEnd('Array.map with from');

console.time('Array.from');
const arr4 = Array.from(arr);
console.timeEnd('Array.from');