Sometimes we wonder about some code, we have just written, how it is performing. In JavaScript, we have a console object. This console object can provide you answer on performance.

Console object has two methods named as time() and timeEnd(). These two methods take requires a string argument, which will name of the timer. It is generally used at the time of testing the code. Below is the syntax:

console.time('Name of the timer')

For Example, We want to test a portion of a code and see the performance. We have a for loop which executes 200000 times. To test the loop we need to start the timer by using console.time(‘testLoop’) before the for a loop. time() will start counting time in the name of ‘testLoop’. After the for loop code ,we need to place console.timeEnd(‘testLoop’). timeEnd() method will stop the counter and print the total time taken by for loop.

// time() will start the timer in name of 'testLoop'
console.time('testLoop')
//For loop will execute 200000 times and print 'i' in console 
for(let i=0;i<200000;i++){
console.log(i)
}
// stop the counter and print the execution time .
console.timeEnd('testLoop')

The output of the above codeĀ  is,

testLoop: 23893.302ms

Please feel free to comment.