DEV Community

Discussion on: JavaScript Performance using console.time() & console.timeEnd()

Collapse
 
bgadrian profile image
Adrian B.G.

I think that this is the definition of "hacky", you change the code you are trying to measure. Is like using console.log instead of breakpoints.

We used this method 5-10yrs ago when we do not have the required tools, but now you do not need them, you have dev tools developers.google.com/web/tools/ch...

Collapse
 
3sanket3 profile image
Sanket Patel

Yes @bgadrian , it is kind of, but a quick way to just check the time consumption of a piece of code. Actually I briefly checked the dev tool's performance feature after reading your comment but found profile seems to have too much application level performance analysis. May be I have to check more tutorials to go in deeper. I would appreciate if you have any suggestions for the same. Thank You!

Collapse
 
bgadrian profile image
Adrian B.G. • Edited

Ok but how would that help you? Most of the time you want to optimize the app or the golden path (or a specific action). To do that you have to find the bottleneck first then optimize it.
The idea is that you do not know what to improve until you benchmark the entire app.

There is a scenario when you want to measure a piece of code, when you do unit benchmarks, when you want to improve an algorithm and compare two versions in paralell. But Im sure there are better ways to do this in JS, like benchmark.js, the lib behind jsperf.com

// add tests
suite.add('old', function() {
  yourOldFunction();
})
.add('new', function() {
  yourNewFunction();
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': false });

The idea is Not to modify your code, but rather test it from the outside.
You can add performance tracking in your TEST files, which will not be bundled in the production.


Also I forgot to mention, the HTML5 added a new API with this purpose, to measure the performance: developer.mozilla.org/en-US/docs/W...

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

The difference is that console is a functionality added by the browser but the performance is a "native" tool.

Thread Thread
 
pranjalagnihot8 profile image
Pranjal Agnihotri {..โค๏ธ}

Hey @adrian , I want to just get the elapsed millisecond for a particular JS function in web-app, is there any simpler way to achieve this without using browser native API. Benchmark.js seems over kill for this use case.