Check the speed of execution in JavaScript

Following is the technique you can use to check the speed of code execution in JavaScript.

  var start = new Date().getTime();
  
  //sample code to test
  for(var i = 0; i <= 1000; i++){
    console.log("Test: " + i);
  }

  var elapsed = (new Date().getTime() - start) / 1000 + " Seconds";

  console.log(elapsed);

Code Explanation

First we create a variable called start and assign the current time using JavaScript's Data() method and get the time in seconds from year 1970 to present using getTime().

 Then write your JavaScript code(It can be anything). Just after your code create a new variable called elapsed and subtract the current time with the value stored in the variable start.

 The console will output the elapsed time in milliseconds, here I've divided the result by 1000 to convert it into the seconds. Following is the screenshot of the Chrome's Web inspector.


Hope this will help you in estimating the code performance. 

If you like this post, then please share your thoughts on how to reduce the execution time or some other techniques you use during the front end development.

Unknown

Hi! I'm Tirumal and I'm a front-end Developer. I love coding, reading and writing blogs. This blog is all about JavaScript and related technologies. Together, let's make the internet beautiful.

0 comments: