Langweiliges Zeug. Was sonst.
JavaScript: benchmark implications on sparse arrays

I tried to benchmark an encryption function by passing an empty array to it:

var data = new Array(10* 1024* 1024);
var start = (new Date).getTime();
rc4.secureEncrypt([1, 2, 3, 4, 5, 6,7,8,9,0], data);
var diff = (new Date).getTime() - start;
alert("spent "+diff+" ms on encryption");

It was slow, but I didn’t know why. I gradually debugged the code and discovered, that 90% of the time was spent in that line:

plantext[i] = encrypted;

Why should accessing a simple array take that long? It’s an O(1) operation! Well, it turns out that the array is a sparse array. Since most of it will never be accessed, it’s simply empty (empty != 0) and is created on first access.
Just filling the array caused the function to be executed 3 to 4 times faster. The encryption itself turned out to be pretty fast, it was just a bad benchmark testing input.

var data = new Array(10* 1024* 1024);
for(var i=0; i < data.length; ++i) data[i]=42;
var start = (new Date).getTime();
rc4.secureEncrypt([1, 2, 3, 4, 5, 6,7,8,9,0], data);
var diff = (new Date).getTime() - start;
alert("spent "+diff+" ms on encryption");