In my attempts to figure out why my js bot execution speed is all over the place, I’ve found it has to do with sorts…
Here are examples TestA and TestB. TestA uses a pre-built sort function. TestB uses the native sort. You can take this code and throw it into any CG IDE that let’s you view the printErr output:
var Environment = this;
var Sorter = function(a,b){
return a.val - b.val;
};
function TestA(){
var s = [];
var elapsed = 0;
var biggest = 0;
var iterations = 0;
while( elapsed < 250000 ) {
var start = Environment.elapsed();
s.sort(Sorter);
var end = Environment.elapsed();
end -= start;
if( end > biggest ) {
biggest = end;
}
iterations++;
elapsed += end;
}
printErr("TESTA: Elapsed time: " + elapsed + " Biggest: " + biggest + " iterations: " + iterations);
}
function TestB(){
var s = [];
var elapsed = 0;
var biggest = 0;
var iterations = 0;
while( elapsed < 250000 ) {
var start = Environment.elapsed();
s.sort();
var end = Environment.elapsed();
end -= start;
if( end > biggest ) {
biggest = end;
}
iterations++;
elapsed += end;
}
printErr("TestB: Elapsed time: " + elapsed + " Biggest: " + biggest + " iterations: " + iterations);
}
TestA();
TestB();
The native sort appears to be (on-average) 3x faster at initializing than the function-based sort. This is so bothersome! Typically, the native sort initializes and sorts an empty array in 30 microseconds or less. Whereas the function-based sort initializes in anywhere from 90 microseconds to 2500 microseconds.
So if you’re ever wondering why a random function took 10 milliseconds to run when it normally takes 140 microseconds… it’s because you’re using custom sorts.
Has anyone seen a way to get around this limitation? I assume it’s something to do with Spidermonkey’s way of implementing sorts.