Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is pop faster than shift?

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.

like image 229
zjmiller Avatar asked Jun 28 '11 03:06

zjmiller


People also ask

What is the difference between pop and shift?

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.

Is Unshift slower than push?

Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.

Is array shift slow?

Because shift() reindex array so the shift method is very slow on large array.

What is Pop Push shift and Unshift?

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.


2 Answers

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.

like image 176
geekosaur Avatar answered Oct 05 '22 04:10

geekosaur


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.

like image 27
Andrew Moore Avatar answered Oct 05 '22 05:10

Andrew Moore