You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript方法与自定义数组插入逻辑的性能差异探讨

数组指定位置插入元素的性能对比与疑问

我尝试在数组指定索引位置插入元素,最初使用JavaScript提供的Array.prototype.slice、Array.prototype.push和Array.prototype.concat等原生方法实现,之后改用基于for循环的自定义逻辑完成相同操作,发现二者存在性能差异。

原生方法实现代码

// Params:
const arr = [1, 2, 3, 4];
const index = 3;
const newItem = 5;

// Steps:
// 1. Create new array from the original one at given index
let start = arr.slice(0, index);

// 2. Add new item to the copy
start.push(newItem);

// 3. Get the rest of the original array
let end = arr.slice(index);

// 4. Print the merged array
console.log(start.concat(end));

自定义for循环实现代码

// Params:
const arr = [1, 2, 3, 4];
const index = 3;
const newItem = 5;

// Steps:
// 1. Create new array from the original one at given index
let copy = [];
for (let i = 0; i < index; i++) {
    copy[copy.length] = arr[i];
}

// 2. Add new item to the copy
copy[index] = newItem;

// 3. Get the rest of the original array
let rest = [];
for (let i = index; i < arr.length; i++) {
    rest[rest.length] = arr[i];
}

// 4. Merge the two arrays
for (let i = 0; i < rest.length; i++) {
    copy[copy.length] = rest[i];
}

// 5. Print the merged array
console.log(copy);

测试结果

  • JavaScript原生方法:101170.7 Ops/sec
  • 自定义逻辑方法:105695.0 Ops/sec

初看差异不大,但考虑日常负载可能在某些场景下较为显著,我有几个疑问:

  • 这种差异是否值得重视?是否应更频繁使用自定义逻辑?
  • 若有更快的数组元素插入方法,恳请分享。
  • 本次基准测试是否公平,是否有更合理的测试方式?

内容的提问来源于stack exchange,提问作者Stan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:24:30