Skip to content

Instantly share code, notes, and snippets.

@kessler
Created July 9, 2016 23:00
Show Gist options
  • Save kessler/cc9a7fe2491d4fe0c54f2c0f3a0195f6 to your computer and use it in GitHub Desktop.
Save kessler/cc9a7fe2491d4fe0c54f2c0f3a0195f6 to your computer and use it in GitHub Desktop.
benchmark of shift vs pop with node.js
'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')
@kessler
Copy link
Author

kessler commented Jul 9, 2016

Weirdly enough, on my machine, when size === 128990 performance are the same:

pop: 32.506ms
shift: 31.557ms

but when size === 128991, performance of shift() dramatically degrades:

pop: 36.992ms
shift: 10631.207ms

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.

@kessler
Copy link
Author

kessler commented Jul 9, 2016

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