JavaScript Benchmarking
I’ve been coding a few functions and methods for an upcoming project and needed to benchmark them. Firebug’s profile tool is pretty good, but it only takes into account one execution of the code – but what if that one instance was particularly slow or particularly fast? For better results, you’d have to repeat the function multiple times to get a better idea of how quick (or slow) it is. So in order to do this, I’ve built a benchmarking tool that bolts onto the Function Prototype:
Function.prototype.benchmark = function(iterations) {
if(iterations === null || isNaN(iterations) || iterations < 1) { throw new TypeError(); }
var begin = (new Date()).getTime();
for(var i = 0; i < iterations; i++) {
this();
}
var end = (new Date()).getTime();
return (end - begin) / iterations; // in milliseconds
};
Use it like this:
var example = function() {
// run some code
};
var benchmark = example.benchmark(100); // run example 100 times
In a nutshell, example is executed 100 times and benchmark contains the average time it took in milliseconds to execute it. Obviously more iterations gives a better average but could potentially crash if the number is too high. For big functions and libraries, I'd recommend starting off low (maybe 100) and then ramping it up but for small functions, you could easily start at up to 10,000 or maybe even 100,000. Make sure there isn't any code in there that could potentially ruin the benchmarking - particularly alerts.
Remember to take into account slow machines and portable devices, as not every browser and computer will do it at the same speed.











