javaScript benchmarking : Console : Compare execution time between two functions / statements

If you want to be one of the best programmers and you are best practice enthusiast then you might wonder for minutes thinking about the standard of the code you have just written or about to write. If you are working on sensitive application that must pass certain performance bench mark then you have to compare the execution time of the statements or functions you are up to.

console.time('test1');
for(i=1; i<1000000; i++)
{
 num = 'My number is ' + 10;
}
time1 = console.timeEnd('test1');
/**
 * Output is
 * test: 25.564ms
 * test: 24.399ms
 * test: 23.234ms
 */
console.time('test2');
for(i=1; i<1000000; i++)
{
 num = 'My number is 10';
}
time2 = console.timeEnd('test2');

if(time1 > time2){
 console.log('Example2 is faster');
}else{
 console.log('Example1 is faster');
}

Or you can be more functional..

function testMethod1(){}
function testMethod2(){}

console.time('test1');
testMethod1();
time1 = console.timeEnd('test1');

console.time('test2');
testMethod2();
time2 = console.timeEnd('test2');

if(time1 > time2){
 console.log('Example2 is faster');
}else{
 console.log('Example1 is faster');
}

You can also refer to my older post I wrote few months back

https://cbabhusal.wordpress.com/2015/01/03/javascript-check-execution-time-of-code-improve-app-performance/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s