Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of unshift() vs. push() in Javascript

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)?

like image 912
dperitch Avatar asked Sep 03 '12 15:09

dperitch


People also ask

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.

What is the difference between push and Unshift in JavaScript?

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.

What does Unshift () mean in JavaScript?

unshift() The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

What is the difference between the array Unshift () and the array shift () elements?

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.


1 Answers

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());

Update

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}`);
like image 124
Shanti Avatar answered Sep 17 '22 19:09

Shanti