JavaScript Benchmarking

I’ve been cod­ing a few func­tions and meth­ods for an upcom­ing pro­ject and needed to bench­mark them. Firebug’s pro­file tool is pretty good, but it only takes into account one exe­cu­tion of the code — but what if that one instance was par­tic­u­larly slow or par­tic­u­larly fast? For bet­ter res­ults, you’d have to repeat the func­tion mul­tiple times to get a bet­ter idea of how quick (or slow) it is. So in order to do this, I’ve built a bench­mark­ing 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 nut­shell, example is executed 100 times and benchmark con­tains the aver­age time it took in mil­li­seconds to execute it. Obvi­ously more iter­a­tions gives a bet­ter aver­age but could poten­tially crash if the num­ber is too high. For big func­tions and lib­rar­ies, I’d recom­mend start­ing off low (maybe 100) and then ramp­ing it up but for small func­tions, you could eas­ily start at up to 10,000 or maybe even 100,000. Make sure there isn’t any code in there that could poten­tially ruin the bench­mark­ing — par­tic­u­larly alerts.

Remem­ber to take into account slow machines and port­able devices, as not every browser and com­puter will do it at the same speed.

Comments

No responses have been made so far. Add your comments.

    What do you think? Leave a comment...