I know what is the difference between unshift()
and push()
methods in JavaScript, but I'm wondering what is the difference in time complexity?
I suppose for push()
method is O(1) because you're just adding an item to the end of array, but I'm not sure for unshift()
method, because, I suppose you must "move" all the other existing elements forward and I suppose that is O(log n) or O(n)?
Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.
Both the methods are used to add elements to the array. But the only difference is unshift() method adds the element at the start of the array whereas push() adds the element at the end of the array.
unshift() The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
The shift() function lets you remove an item from the start of an array. The the unshift() function adds one or more items to the start of an array.
push() is faster.
js>function foo() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.unshift(1); return((new Date)-start)} js>foo() 2190 js>function bar() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.push(1); return((new Date)-start)} js>bar() 10
function foo() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.unshift(1); return((new Date)-start)} console.log(foo()) function bar() {a=[]; start = new Date; for (var i=0;i<100000;i++) a.push(1); return((new Date)-start)} console.log(bar());
The above does not take into consideration the order of the arrays. If you want to compare them properly, you must reverse the pushed array. However, push then reverse is still faster by ~10ms
for me on chrome with this snippet:
var a=[]; var start = new Date; for (var i=0;i<100000;i++) { a.unshift(1); } var end = (new Date)-start; console.log(`Unshift time: ${end}`); var a=[]; var start = new Date; for (var i=0;i<100000;i++) { a.push(1); } a.reverse(); var end = (new Date)-start; console.log(`Push and reverse time: ${end}`);
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