简体   繁体   English

更快地混合两个 javascript 列表

[英]Mix two javascript lists faster

I have two list x_values and y_values such as :我有两个列表 x_values 和 y_values 例如:

x_values = [x1, x2, ...., xN];
y_values = [y1, y2, ...., yN];

I would like to create a list result such as :我想创建一个列表结果,例如:

result = [[x1, y1], [x2, y2], .... [xN, yN]]

Currently I am doing the following :目前我正在做以下事情:

let result = [];

// Format new data
for (let j = 0; j < x_values.length; j++) {
   result.push([x_values[j], y_values[j]]);
}

This is working, but when N is very high, this script is really slow (I need to execute it multiple times per second)这是有效的,但是当 N 非常高时,这个脚本真的很慢(我需要每秒执行多次)

Do you have any way to accelerate the generation of this list ?你有什么办法可以加速这个列表的生成吗?

Thanks :)谢谢 :)

Use the map method:使用地图方法:

var a = ['a1', 'a2', 'a3']
var b = ['b1', 'b2', 'b3']
var c = a.map(function(e, i) {
 return [e, b[i]];
});

As mentioned here .正如这里提到的。

The time complexity of this function is also "O(n)".这个函数的时间复杂度也是“O(n)”。 Not sure if there is a faster way to do it.不确定是否有更快的方法来做到这一点。 If the idea is to access the information in the 2 lists later on in the code you could just keep these lists the way they are and then just access the index directly as needed.如果想法是稍后在代码中访问 2 个列表中的信息,您可以保持这些列表的原样,然后根据需要直接访问索引。 That could make your list processing faster as the time complexity of accessing the list would then be O(1)这可以使您的列表处理速度更快,因为访问列表的时间复杂度为 O(1)

One thing you can do is to use index instead of push.您可以做的一件事是使用索引而不是推送。 Another thing is to create the result array with a given length first.另一件事是首先创建具有给定长度的结果数组。 Here is a benchmark comparison.是一个基准比较。

let result = new Array(x_values.length);
for (let j = 0; j < x_values.length; j++) {
   result[j] = [x_values[j], y_values[j]];
}

Also, Array.forEach and Array.map are definitely slower than for-loops.此外, Array.forEachArray.map肯定比 for 循环慢。 This is due to the fact that they construct a new context ( this , local namespace, etc) every time the function passed to them is called.这是因为每次调用传递给它们的函数时,它们都会构造一个新的上下文( this 、本地命名空间等)。 Functional programming in JS often makes code cleaner at the cost of performance. JS 中的函数式编程通常以牺牲性能为代价使代码更简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM