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