javascript - 为什么 Array 的自定义实现比原生 JavaScript Array 更高效?

标签 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
  }

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

我还是不太明白为什么这样性能更好、速度更快?因为我在新的 Array 类方法上使用原生 JavaScript Arrays 方法...

我将不胜感激。

最佳答案

问题一定来自您的数据和/或其结构。 这是一些粗略的证明,您的自定义类并不总是比 native 数组更高效。

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

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

关于javascript - 为什么 Array 的自定义实现比原生 JavaScript Array 更高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54860439/

相关文章:

javascript - 增加共享点跨域库中的响应大小限制

javascript - 映射来自 Twitch API 的评论 - React

PHP 将一个数组附加到另​​一个数组(不是 array_push 或 +)

javascript - 为什么es6 Set原型(prototype)有values方法?

javascript - Node.js 泄漏 for..in 循环

mysql - 选择数组、子查询和多行结果

python - c malloc数组指针在cython中返回

javascript - 为什么在 Javascript 中使用类数组对象而不是原生数组

嵌套表中的javascript

javascript - 如何在一个 iMacros 脚本中使用多个循环进行锻炼?