MST

星途 面试题库

面试题:JavaScript中不同数组创建方式在大量数据场景下的性能差异

假设有一个需求,要创建一个包含10万个随机整数的数组。分别使用 `new Array()` 构造函数、数组字面量 `[]` 以及 `Array.from()` 方法来创建数组,并编写性能测试代码,分析在这种大量数据场景下,这几种创建方式的性能差异,说明原因。
39.3万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

使用 new Array() 构造函数创建数组

function createArrayWithConstructor() {
    return new Array(100000).fill(0).map(() => Math.floor(Math.random() * 100));
}

使用数组字面量 [] 创建数组

function createArrayWithLiteral() {
    const arr = [];
    for (let i = 0; i < 100000; i++) {
        arr.push(Math.floor(Math.random() * 100));
    }
    return arr;
}

使用 Array.from() 方法创建数组

function createArrayWithFrom() {
    return Array.from({ length: 100000 }, () => Math.floor(Math.random() * 100));
}

性能测试代码

function testPerformance(func, name) {
    const start = Date.now();
    func();
    const end = Date.now();
    console.log(`${name} 耗时: ${end - start} ms`);
}

testPerformance(createArrayWithConstructor, 'new Array() 构造函数');
testPerformance(createArrayWithLiteral, '数组字面量 []');
testPerformance(createArrayWithFrom, 'Array.from() 方法');

性能差异及原因分析

  1. new Array() 构造函数
    • 性能表现:在填充和映射操作时,由于数组已经预先分配了内存,理论上性能会较好。但是 fillmap 操作会遍历数组,存在一定开销。
    • 原因:先使用 fill 方法填充数组,再用 map 进行映射,虽然数组内存预先分配,但两次遍历操作增加了时间复杂度。
  2. 数组字面量 []
    • 性能表现:性能相对较差。
    • 原因:在 for 循环中使用 push 方法向数组添加元素,每次 push 都可能涉及数组的扩容操作,这会导致频繁的内存重新分配和数据复制,增加了性能开销。
  3. Array.from() 方法
    • 性能表现:性能较好。
    • 原因:Array.from() 方法直接根据指定长度创建数组,并通过回调函数一次性生成所有元素,避免了像数组字面量方式中频繁的数组扩容操作,同时也比 new Array() 构造函数少了一次 fill 的遍历操作,所以性能相对较好。