node环境js unshift push 性能开销测试

335 阅读1分钟

背景是最近遇到了一个大数组场景,想了解一下,直接unshift构建数组和先push到数组,再reverse,哪一个性能更好。因为不清楚js的runtime具体底层是如何实现js数组的

结论:在node环境(16.1.0 windows)下,测试js的unshift性能应该是O(n),而push是O(1),因此如果对场景性能要求,可以多善用push,少用unshift

let test = () => {
  let arr1 = []
  let arr2 = []
  let arr3 = []
  let start = Date.now()
  for (let i = 0; i < 100000; i++) {
    arr1.push(i)
  }
  let end1 = Date.now()
  for (let i = 0; i < 100000; i++) {
    arr2.unshift(i)
  }
  let end2 = Date.now()
  for (let i = 0; i < 100000; i++) {
    arr3.push(i)
  }
  arr3.reverse()
  let end3 = Date.now()
  console.log(`100000 times of push cost ${end1 - start} ms`)
  console.log(`100000 times of unshift cost ${end2 - end1} ms`)
  console.log(`100000 times of push and reverse cost ${end3 - end2} ms`)
}

test()

// 100000 times of push cost 3 ms
// 100000 times of unshift cost 913 ms
// 100000 times of push and reverse cost 3 ms