Saturday, 25 July 2015

How to Calculate Execution Time of a Code Block in JavaScript?

    Finding execution of a block of code in any programming language helps you to write better code. In JavaScript, using console.time and console.timeEnd functions you can measure the amount of time a code block takes to run.

Let's take a look at how to use console.time() and console.timeEnd() in a working example.

Here is a sample code block, which creates 100 simple JavaScript objects using the new keyword inside a while loop.
console.time("10 objects in while loop");

function NewObj(param) {
 this.value = param;
}

var i = 0;
var obj;
while(i < 10) {
 obj = new NewObj(i);
 i++;
 console.log(obj.value);
}

console.timeEnd("10 objects in while loop");

Note: you need to pass same label (String) to console.time() and console.timeEnd() functions, otherwise, it won't give you the elapsed time.

From the below screenshot, we can see our block of code took 3.000 ms. Remove console.log() statements and see how much time it'll take to execute.

The result in Screenshot is below. 


How to Execute above Code:

I have executed the above code in Google Chrome. In Google Chrome, open JavaScript console, by pressing Ctrl+Shift+J. Paste the code in JSConsole and hit enter. The browser runs the code and gives you the result. You can execute the code in any modern browser such as Firefox, Internet Explorer, Safari.



When to use console.time :

The console.time() method allows developers to have an understanding of what code affects performance and what doesn't. It gives the results based on browser, operating system and system hardware you're using.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.