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

前端 未结 5 904
时光取名叫无心
时光取名叫无心 2020-12-04 17:23

I know what is the difference between unshift() and push() methods in JavaScript, but I\'m wondering what is the difference in time complexity?

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 18:14

    One way of implementing Arrays with both fast unshift and push is to simply put your data into the middle of your C-level array. That's how perl does it, IIRC.

    Another way to do it is have two separate C-level arrays, so that push appends to one of them, and unshift appends to the other. There's no real benefit to this approach over the previous one, that I know of.

    Regardless of how it's implemented, a push or and unshift will take O(1) time when the internal C-level array has enough spare memory, otherwise, when reallocation must be done, at least O(N) time to copy the old data to the new block of memory.

提交回复
热议问题