简体   繁体   English

将元素添加到Uint8ClampedArray类型化数组的快速方法

[英]Fast way to add elements into an Uint8ClampedArray typed array

Working on some pixel manipulation and need to speed up an algorithm that adds elements into an array. 需要进行一些像素操作,并且需要加快将元素添加到数组中的算法。 Right now i'm throwing away the typed array that the pixels come from during the algorithm. 现在,我正在抛弃算法期间像素来自的类型化数组。 Is there a fast way to add elements to a typedArray, and if not do you see any improvements that could be done to my current algorithm? 有没有一种快速的方法可以将元素添加到typedArray中,如果没有,您是否可以对当前算法进行任何改进?

My current algorithm looks like this (simplified and with indexesToAdd ascending): 我当前的算法如下所示(已简化,并且使用indexsToAdd递增):

//Example input and output
//indexesToAdd = [0,3,4]; // Normally around 4000 elements
//typedArray = [100,200,40,50,100]; // Normally around 1 million elements
//Output = [100,0,200,40,50,0,100,0];
function addIndexes(indexesToAdd, typedArray) {
  var newArray = [];
  var index = 0;

  for(var i=0;i<typedArray.length;i++) {
    if (i != indexesToAdd[index]) {
      newArray.push(typedArray[i]);
    } else {
      newArray.push(typedArray[i], 0);
      index++;
    }
  }

  return newArray;
}

I thought of using splice but Uint8ClampedArray doesn't have this ability. 我想到使用拼接,但Uint8ClampedArray不具备此功能。 I also tried converting the Uint8ClampedArray to a regular array so I could use splice but this conversion process was 10x as long as the algorithm. 我还尝试将Uint8ClampedArray转换为常规数组,以便可以使用拼接,但是此转换过程是算法的10倍。

Consider the following: 考虑以下:

  • Construct a Uint8ClampedArray TypedArray instead of the standard Array ─ this would lower memory consumption and speed up writes 构造一个Uint8ClampedArray TypedArray而不是标准Array -这将降低内存消耗并加快写入速度
  • Remove line duplicates and the unnecessary else block 删除行重复项和不必要的else块
  • Prepopulate max iterations 预填充最大迭代
  • Use strict comparison 使用严格的比较

Try this code runs X7-10 times faster (15ms vs 105ms ─ 1M items) : 尝试使用此代码将运行速度提高X7到10倍(15ms vs 105ms─1M项):

function addIndexes(indexesToAdd, typedArray) {
  var newArray = new Uint8ClampedArray(indexesToAdd.length + typedArray.length);
  var index = 0;
  var max = typedArray.length;
  var c = 0;
  for(var i=0;i<max;i++) {
    newArray[c] = typedArray[i];
    if (i !== indexesToAdd[index]) {
      c++;
      newArray[c] = 0;
    }
    c++;
    index++;
  }
  return newArray;
}

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

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