Most efficient way to prepend a value to an array

后端 未结 9 1132
予麋鹿
予麋鹿 2020-12-02 04:53

Assuming I have an array that has a size of N (where N > 0), is there a more efficient way of prepending to the array that would not require O(N

9条回答
  •  无人及你
    2020-12-02 05:19

    I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:

    var a = [1, 2, 3, 4];
    a.unshift(0);
    a; // => [0, 1, 2, 3, 4]
    

    [Edit]

    This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:

    a.slice().unshift(0); // Use "slice" to avoid mutating "a".
    

    [Edit 2]

    For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:

    function prepend(value, array) {
      var newArray = array.slice();
      newArray.unshift(value);
      return newArray;
    }
    
    var x = [1, 2, 3];
    var y = prepend(0, x);
    y; // => [0, 1, 2, 3];
    x; // => [1, 2, 3];
    

提交回复
热议问题