DEV Community

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

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.