[英]What is the fastest way to replace a section of an array with another array in Javascript?
I'm working with Dygraph and have implemented a reloader which adds higher resolution data as the user zooms into a graph. 我正在与Dygraph合作,并实现了一个重新加载程序,该加载程序可以在用户放大图形时添加更高分辨率的数据。
In order to keep the original file boundaries, I'm keeping the original data and insert the newly loaded data at the respective zoom interval like so: 为了保持原始文件的边界,我保留了原始数据并以相应的缩放间隔插入新加载的数据,如下所示:
function spliceAndInject(my_graph_gadget, my_hi_res_data_dict) {
...
for (i = 0, len = current_data_set.length; i < len; i += 1) {
point = current_data_set[i];
// NOTE: a point = [time_in_milliseconds, value_for_graph]
timer = point[0];
if (timer < lower_bound || timer > higher_bound) {
new_data_set.push(point);
} else if (is_injected === undefined) {
is_injected = true;
new_data_set = new_data_set.concat(hi_res_data_set);
}
}
...
}
I'm wondering whether this could be done any faster, because the graph rendering gets notably slower the more data I'm carrying around. 我想知道是否可以更快地完成此操作,因为随着我携带的数据越多,图形渲染的速度会明显变慢。
Question : 问题 :
What is the fastest way to replace a section of an array with another array? 用另一个数组替换数组的一部分的最快方法是什么?
Thanks! 谢谢!
If you know the indices beforehand and want to modify the array with the data, using the native splice
method is probably the best - although for optimized performance you'd need to test against a hand-written solution that manually does the moving. 如果您事先知道索引并想用数据修改数组,则使用本机
splice
方法可能是最好的方法-尽管要获得最佳性能,您需要针对手动移动的手写解决方案进行测试。
If you want to create a new array, I'd use this: 如果要创建一个新数组,请使用以下命令:
var len = current_data_set.length,
new_data_set = new Array(len);
for (var i=0; i<len; i++)
var point = current_data_set[i];
if (point[0] < lower_bound)
new_data_set[i] = point;
else
break;
for (var j=i, k=0, l=hi_res_data_set.length; k<l; k++)
new_data_set[j++] = hi_res_data_set[k];
for (; i<len; i++)
if (current_data_set[i][0] > higher_bound)
break;
for (; i<len; i++)
new_data_set[j++] = current_data_set[i];
I think this is faster than yours because 我认为这比您的速度快,因为
concat
which creates a second new array concat
来创建第二个新数组 lower_bound
and higher_bound
lower_bound
和higher_bound
测试所有点 is_injected
variable (which should be statically typed as a boolean if at all), whose only purpose is to jump over a loop section is_injected
变量(如果有的话,应该静态地将其键入为布尔值),其唯一目的是跳过循环部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.