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?
My current algorithm looks like this (simplified and with indexesToAdd ascending):
//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. 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.
Consider the following:
Try this code runs X7-10 times faster (15ms vs 105ms ─ 1M items) :
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;
}