Testing array element removal - some elements
Comparing Array.protoype.splice() to manual removal methods while removing a small number of elements.
by sansegot
JavaScript
//----------------------------------------------------------
// Helper functions
//----------------------------------------------------------
function log(msg) {
$(document.body).append("<br>"+msg);
}
function checkSum(arr) {
var sum = 0;
for(var i=0, maxI=arr.length;i<maxI;i++) {
sum+=arr[i];
}
return(sum);
}
var arrOriginal=[],
arrA,
arrB,
maxI = 100000,
start,
end,
i=0, j=0,
itemsToBeRemoved = [5,15,115,1115,11115,51111,5111,511,51];
itemsToBeRemoved.sort(function(left, right) { if(left===right) return(0); return(left>right ? 1 : -1); });
//----------------------------------------------------------
// Preparing Array
//----------------------------------------------------------
// fill the array with random values, so that checkSum can compare the resulting arrays
for(i=0;i<maxI;i++) {
arrOriginal[i] = Math.random()*100;
}
//----------------------------------------------------------
// TEST 1 - splice
//----------------------------------------------------------
arrA= arrOriginal.slice(); // create a copy of the original array
i=itemsToBeRemoved.length;
start = new Date();
// remove all the odd elements
while(i-- > 0) {
arrA.splice(itemsToBeRemoved[i], 1);
}
end = new Date();
log((end.getTime() - start.getTime())+"# splice (checksum="+checkSum(arrA)+")");
//----------------------------------------------------------
// TEST 2 - copy + override + reverse
//----------------------------------------------------------
arrA= arrOriginal.slice(); // create a copy of the original array
start = new Date();
arrB = [];
i=maxI;
j=0;
z=itemsToBeRemoved.length-1;
// copy even items to a new array
while(i-- > 0) {
if(i!==itemsToBeRemoved[z]) {
arrB[j++] = arrA[i];
} else {
console.log(itemsToBeRemoved[z]);
// if all the items have been removed
if(z--===0) {
z--;
}
}
}
// override the old array with the new one - array is NOT preserved (all the references to this array need to...