HACKER Q&A
📣 Exuma

What's Your JavaScript Performance “Gotcha” or Tip?


I'll start... I just learned that Javascript's "shift" operation is O(n) and not O(1).

I always thought both queue operations (shift/unshift) were somehow implementing a queue under the hood, but now is obvious in retrospect that it's not... simply due to the fact that what's actually under the hood is an ArrayList (or some V8 optimized rendition of it, perhaps).

I was watching an algorithm course, and this one surprised me. He also mentioned, many people get that wrong in coding interviews when asked to implement a queue which may involve 100's of thousands of items.


  👤 cwdegidio Accepted Answer ✓
It makes sense. It is an array. When you remove the first element, all elements in the array have to shift to their new indices "left" (one less than their previous index). When you unshift, all elements must move their indices up by 1, to the "right". In theory it is staying at the same memory address (unless unshifting causes the array to double in size to account for further growth... then it will be given a new memory address).