shift 和 unshift 函数的时间复杂度问题
测试
关于在数组中使用 shift()
和 unshift()
方法,基于数组的特性,相较于 pop()
和 push()
方法应该是会存在时间复杂度上的劣势的。
下面就用代码验证一下自己的想法:
/**
* shift 和 unshift 数组方法时间复杂度测试
*/
function getTestArrSample(length) {
const arr = []
while (length--) {
arr.push(getItemSample())
}
return arr
}
function getItemSample() {
return Math.floor(Math.random() * 10000)
}
const testSample = getTestArrSample(100000)
let startTime = +new Date()
let times = 1000
while (times--) {
testSample.unshift(1)
// testSample.shift()
// testSample.push(1)
// testSample.pop()
}
const duration = +new Date() - startTime
console.log(duration)
通过轮流注释下面几行代码,就得出了,以下结果
testSample.unshift(1)
// testSample.shift()
// testSample.push(1)
// testSample.pop()
方法 | 次数 | 多次运行平均时间 |
---|---|---|
unshift | 1000 | 29ms |
unshift | 10000 | 315ms |
shift | 1000 | 27ms |
shift | 10000 | 242ms |
push | 1000 | 0ms |
push | 10000 | 0.5ms |
pop | 1000 | 0ms |
pop | 10000 | 0.5ms |
总结
因为数组是在有序排列的数据结构,在进行 unshift()
和 shift()
操作时,需要在数组的开始位置插入或删除元素,导致整个数组的其他元素均需要移动,这样就导致了需要大量时间进行数组元素移动操作,时间复杂度为 O(n)。
在开发中如果需要进行长度较大的数组进行操作,应该尽量避免大量使用 unshift()
和 shift()
操作。不过也不必太过于严格规避,毕竟大多数时候并没那么大长度的数组,而且如只进行少量操作,所用的额外时间一般不会产生负面影响。
评论
全部评论 (0)