Created
July 9, 2016 23:00
-
-
Save kessler/cc9a7fe2491d4fe0c54f2c0f3a0195f6 to your computer and use it in GitHub Desktop.
benchmark of shift vs pop with node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const size = 130000 | |
let arr1 = new Array(size) | |
let arr2 = new Array(size) | |
for (let i = 0; i < size; i++) { | |
arr1[i] = i + '' | |
arr2[i] = i + '' | |
} | |
console.time('pop') | |
for (let i = 0; i < size; i++) { | |
let r = arr1.pop() | |
if (r > size) console.log(1) | |
} | |
console.timeEnd('pop') | |
console.time('shift') | |
for (let i = 0; i < size; i++) { | |
let r = arr2.shift() | |
if (r > size) console.log(1) | |
} | |
console.timeEnd('shift') |
Reversing the array seems to work:
'use strict'
const size = 128991
let arr1 = new Array(size)
let arr2 = new Array(size)
let arr3 = new Array(size)
for (let i = 0; i < size; i++) {
arr1[i] = i + ''
arr2[i] = i + ''
arr3[i] = i + ''
}
console.time('pop')
for (let i = 0; i < size; i++) {
let r = arr1.pop()
if (r > size) console.log(1)
}
console.timeEnd('pop')
console.time('shift')
for (let i = 0; i < size; i++) {
let r = arr2.shift()
if (r > size) console.log(1)
}
console.timeEnd('shift')
console.time('reverse')
arr3.reverse()
for (let i = 0; i < size; i++) {
let r = arr3.pop()
if (r > size) console.log(1)
}
console.timeEnd('reverse')
results in:
pop: 35.088ms
shift: 10421.718ms
reverse: 37.479ms
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Weirdly enough, on my machine, when size === 128990 performance are the same:
but when size === 128991, performance of
shift()
dramatically degrades:Tested this also on an amazon linux machine, got the same behaviour. Leading me to believe that it's part of some underlying optimization, rather than a direct effect of hardware.