JavaScript performance tests
Oct 19, 2013     21:11:40

When we developing simple JS app / website we don't even need to test something. If everything is simple - there is no reason to make it hard.

But while developing plugins, libraries, or a project with fat ("powerful") client-side part, JavaScript performance has much higher priority.

The are a lot of ways to test different cases:

  • JSPerf.com - JavaScript performance playground;
  • console.time() method of testing some code part performance;
  • console.time('timerName');
    /* your code */
    console.timeEnd('timerName');
  • Self written timers;

JSPerf.com

This is the coolest project ever for comparing few different code performance parts.

And there is a lot of test already written by other developers - http://JSPerf.com/browse

The main plus after testing performance with this JSPerf - you can learn something new, some better practices from other developers, who already investigate the issue you've been interested in.


console.time

Console time is native console method for modern browsers.

The usage of it is very easy.

1. Start your timer:

console.time('Name of your timer here')

2. Your code that you want to test:

/* Some code */
var arr = [];
for (var i = 0; i < 100500; i++) {
    arr.push(Math.random()*2);
    // arr[i] = Math.random()*2; // in other test
}

3. End your timer:

console.timeEnd('Name of your timer here')

After that you'll see the result in your console.


Self written timers

The easies example of self written timers:

var timerStart = function(){
    return (new Date()).getTime(); // => current time in timestamp
};
var timerEnd = function(start){
    return (new Date()).getTime() - start; // => current time in timestamp subtract start time
};

The usage is almost the same as for timers:

1. Start your timer:

var tmp_start = timerStart()

2. Your code that you want to test:

/* Some code */
var arr = [];
for (var i = 0; i < 100500; i++) {
    arr.push(Math.random()*2);
    // arr[i] = Math.random()*2; // in other test
}

3. End your timer:

// log to console
console.log('Name of your timer here = ' + timerEnd( tmp_start ));
// or do something else, for example - push timer result to an array
your_app_timers_variable.push( timerEnd( tmp_start ) );

Example

Lets try to test two ways of creation an array with random values.

1. with push();

var t1 = [];
for (var i = 0; i < arr_length; i++) {
    t1.push(Math.random() * 2);
}

2. index assignment;

var t2 = [];
for (var i = 0; i < arr_length; i++) {
    t2[i] = Math.random() * 2;
}

Click buttons to run tests with different array length and look in your console to view results. Test will be executer 10000 times, so be patient.


Conclussion

Always test your code performance! Because sometimes the easiest way is not the best way.


blog comments powered by Disqus