将值添加到数组的最有效方法 [英] Most efficient way to prepend a value to an array

查看:226
本文介绍了将值添加到数组的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的数组大小为 N (其中 N> 0 ),是否有一个更有效的方法是在数组之前不需要O(N + 1)步骤?

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 + 1) steps?

在代码中,基本上,我目前正在做的是

In code, essentially, what I currently am doing is

function prependArray(value, oldArray) {
  var newArray = new Array(value);

  for(var i = 0; i < oldArray.length; ++i) {
    newArray.push(oldArray[i]);
  }

  return newArray;
}


推荐答案

我不确定在big-O方面效率更高,但肯定使用 unshift 方法更简洁:

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]

jsPerf基准显示至少在几个浏览器中, unshift 速度要快得多,无论可能不同的大O性能如果你可以修改数组-地点。如果你真的不能改变原始数组,那么你会做类似下面的代码片段,它似乎没有你的解决方案快得多:

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".

为了完整性,可以使用以下函数代替OP的示例 prependArray(...)来利用数组 unshift (...)方法:

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];

这篇关于将值添加到数组的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆