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