简体   繁体   中英

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.

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.

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

  • it doesn't use concat which creates a second new array
  • it doesn't test all points against lower_bound and higher_bound
  • it doesn't use that odd is_injected variable (which should be statically typed as a boolean if at all), whose only purpose is to jump over a loop section

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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