当前位置: 代码迷 >> JavaScript >> 为什么Array的自定义实现比本机JavaScript Array更高效?
  详细解决方案

为什么Array的自定义实现比本机JavaScript Array更高效?

热度:101   发布时间:2023-06-05 14:05:15.0

我正在解决一个涉及一些循环和计算新数组的挑战。 我的解决方案适用于相当小的阵列但是在10k +项目的大型阵列上失败了。 我收到了“超时错误”

然后我实现了自己的数组,如:

  class MyArray {
    constructor(initialArray) {
      this.length = initialArray.length
      this.data = initialArray
    }
    get(index) {
      return this.data[index]
    }
    push(item) {
      this.data[this.length] = item
      this.length++
      return this.data
    }
    pop() {
      const lastItem = this.data[this.length - 1]
      delete this.data[this.length - 1]
      this.length--
      return lastItem
    }
    /// etc
  }

然后我用给定的数组启动它并使用我的数组方法来执行计算,它甚至适用于赋值的大数组。

我仍然不明白为什么这种性能更高更快? 因为我在我的新Array类方法上使用本机JavaScript Arrays方法...

我希望得到更多的澄清。

问题必须来自您的数据和/或其结构。 这里有一些粗略的证明,您的自定义类并不总是比本机数组更高性能。

 class MyArray { constructor(initialArray) { this.length = initialArray.length this.data = initialArray } get(index) { return this.data[index] } push(item) { this.data[this.length] = item this.length++ return this.data } pop() { const lastItem = this.data[this.length - 1] delete this.data[this.length - 1] this.length-- return lastItem } } const TESTS = 100000 // 100k // Custom let myCustomArray = new MyArray([]) console.time('customClassPush'); for (let i = 0; i < TESTS; i++) { myCustomArray.push(i) } console.timeEnd('customClassPush'); console.time('customClassGet'); for (let i = 0; i < TESTS; i++) { myCustomArray.get(i) } console.timeEnd('customClassGet'); console.time('customClassPop'); for (let i = 0; i < TESTS; i++) { myCustomArray.pop() } console.timeEnd('customClassPop'); // Native let myNativeArray = [] console.time('nativeArrayPush'); for (let i = 0; i < TESTS; i++) { myNativeArray.push(i) } console.timeEnd('nativeArrayPush'); console.time('nativeArrayGet'); for (let i = 0; i < TESTS; i++) { myNativeArray[i] } console.timeEnd('nativeArrayGet'); console.time('nativeArrayPop'); for (let i = 0; i < TESTS; i++) { myNativeArray.pop() } console.timeEnd('nativeArrayPop'); 

多次运行以获得更多可能的结果,以便您可以对其进行一些统计以获得更精确的数据。

  相关解决方案