Shift() and unshift() array methods are methods that occurs at the beginning of an array while pop() and push() operates at the back.
pop() and push() are said to be faster than shift() and unshift() but why is that so? Let's discuss it more down below.
let's discuss their time complexities
consider having an array of 10 elements
arr = [10, 12, 2, 3, 7, 100, 8, 28, 10, 1]
the first element is at index 0 as arrays are zero-indexed once you want to do any operation at the front of the array either adding or removing the rest of the array elements will have to be indexed
e.g * add 15 at index 0
when you do arr.unshift(15), the element that was at index 0 will need to be pushed one value behind so that the newly added value get index 0 and so on for other elements re-indexing
which is similar to arr.shift() which removed 10 and have 12 be pushed forward to occupy index 0 and so on
thus, this re-indexing will occur n number of times where n is the number of array elements
However, for push and pop since we are affecting at the back there is no need to re-index thus its on a single operation that we are doing i.e if you push something at the end the elements that existed in the array won't be affected
To sum up, we have seen that for push and pop the operation will occur only once at constant time hence their time complexity is O(1) and for shift and unshift whose operations occurs n number of times their time complexity is O(n).
which means pop and push are faster than shift and unshift because they have an efficient** time complexity** of O(1)
Top comments (0)