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

前端 未结 5 908
时光取名叫无心
时光取名叫无心 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 17:58

    The JavaScript language spec does not mandate the time complexity of these functions, as far as I know.

    It is certainly possible to implement an array-like data structure (O(1) random access) with O(1) push and unshift operations. The C++ std::deque is an example. A Javascript implementation that used C++ deques to represent Javascript arrays internally would therefore have O(1) push and unshift operations.

    But if you need to guarantee such time bounds, you will have to roll your own, like this:

    http://code.stephenmorley.org/javascript/queues/

提交回复
热议问题