loading...

re: Is JavaScript's .shift() Method a Performance Boost? VIEW POST

FULL DISCUSSION
 

Hey just to point out that shift itself is a bit of a pain doing it frequently - that's because a shift "might" have to move all of the elements in the array (it's not allocating fortunately) - it depends on the actual engine implementation - but it's likely.

push and pop are very fast operations because they only change the length of the array, unshift and shift have to move all of the items in the array (because the operate at the beginning). So depending on what you are doing it might be wise to reverse and array and operate at the end - really would have to be a lot of operations though.

In the case of a rotate you can use the fact that .splice returns the items it removes so rotateLeft to me looks like:

    function rotateLeft(array, n) {
      n = n % array.length
      return array.push(...array.splice(0, n))
    }

Effectively push on the end the items you removed from the front. The cost of this is an array the size of the items you removed. But no loop.

 

Thanks Mike for pointing out the potential costly operation of shift -- I read somewhere that also compared shift with push and pop, but your explanation makes more sense to me. And yes, using splice first and adding the specific items to the array via spread operator does look more efficient. Really appreciate your help! :)

 

Yeah we can do it without spread - but now it looks nicer in ES6 :)

    function rotateLeft(array, n) {
      n = n % array.length
      return array.push.apply(array, array.splice(0, n))
    }
 

It looks like you could get better perf (at least for long arrays) using Array#concat without the spread operator:

jsperf.com/concat-vs-spreader

Also remember that Array#push returns the pushed item new length of the array, not the array 😉

 

You're right, should have a , array at the end I guess or a separate line

code of conduct - report abuse