为什么Array的自定义实现比本机JavaScript Array更有性能?

时间:2019-02-25 06:14:49

标签: javascript arrays

我正在解决一个挑战,其中涉及对新数组进行一些循环和计算。我的解决方案适用于相当小的阵列,但对于包含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
  }

然后,我使用给定的数组启动此操作,并使用我的arrays方法执行计算,即使给定分配的大数组也可以使用。

我还是不太明白为什么这样的性能更高,速度更快?由于我在新的Array类方法上使用本机JavaScript Arrays方法...

我希望对此进行更多的澄清。

1 个答案:

答案 0 :(得分:1)

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

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');

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

相关问题