Saturday 19 July 2008

Timing is everything

Here for your delight.

A simple way to track timing in Javascript.

[cc lang="php" tab_size="2" lines="40"]
// TIMESTAMP Function
function timestamp(){return (new Date()).valueOf();}

// TIMER Function, wraps timing arround function call
function timer(f){
var t1 = timestamp();
for(var i = 0; i < 1000; i++){
var t2 = timestamp();
return t2-t1;

// The function to test
var testFunc = function(){
var v = (window["DoYouBelieveInSpeedReading"])?true,false;
// Now call the timer
alert("time taken="+(timer(testFunc)/1000) + " seconds" );

The core is converting a date object into milliseconds: date.getValueOf(). This will give you a Long of the number of millseconds since 1970.

so var t1 = timestamp(); will store the start time.

Then do the thing you want to test... I would suggest a very large number of times... I needed to make it 100,000 for the Regex below.

and var t2 = timestamp(); becomes the end time.

Now totalTimeTaken = t2 -t1; in millseconds.

Finally time = totalTimeTaken/1000; to get the number of seconds that the function took.

I wrapped it all up in a function timer...

which can be called by
alert("time taken="+timer(myFunc)/1000);

I recently used this to test String matching functions, to find that indexOf is blisteringly fast, followed closely by pattern.test, and then way behind that String.match .

For 100,000 repetitions:
String.match: 1300ms
pattern.test: 360ms
String.indexOf: 180ms

So the moral of todays story is...

  • use indexOf if you can

  • pattern.test if you must have REGEX or more than one match

  • and AVOID String.match if you can

Just remember that premature optimization is a bad thing...

Happy Testing...!

No comments:

Post a Comment