Douglas Crockford, in JavaScript: The Good Parts, states that "shift is usually much slower than pop". jsPerf confirms this. Does anyone know why this is the case? From an unsophisticated point of view, they seem to be doing pretty much the same thing.
Shift() and pop() methods are used to remove an element from an array. But there is a slight variation between them. The method shift() is used to remove the first element from an array, whereas the pop() method is used to remove the last method from the array.
Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.
Because shift() reindex array so the shift method is very slow on large array.
pop() removes the last element of an array. push() adds an element to the end of an array. shift() removes the first element. unshift() adds an element to the beginning of the array.
To remove the returned item without re-addressing the array and invalidating all references to it, shift()
requires moving the entire array around; pop()
can simply subtract 1 from its length.
shift()
has to re-index the whole array while pop()
doesn't.
pop()
simply removes the last element in the array. Therefore, the elements do not move; simply the .length
has to be updated.
shift()
removes the first element in the array. This requires a re-indexing of all elements in the array, so that [1]
becomes [0]
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With