Testing array element removal

comparing Array.prototype.splice() to other element removal methods

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;

//----------------------------------------------------------
// 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=maxI;

start = new Date();

// remove all the odd elements
while(i-- > 0) {
	arrA.splice(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;

// copy even items to a new array
while(i > 0) {
	i-=2; // skip two elements
	arrB[j++] = arrA[i];
}

// override the old array with the new one - array is NOT preserved (all the references to this array need to be updated manually)
arrA = arrB.reverse(); // reverse the order of the elements

end = new Date();
log((end.getTime() - start.getTime())+"# copy + override (checksum="+checkSum(arrA)+")");

//----------------------------------------------------------
// TEST 3 - copy + splice() + push()
//----------------------------------------------------------
arrA= arrOriginal.slice(); // create a copy of the...