DEV Community

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

Collapse
 
varoman profile image
varo manukyan

Unfortunately, this kind of performance measurements are useless.

  1. You can't measure the performance of the entire application
  2. Every time you re-run it will produce completely different results, so you can't event say how long it will take a particular function to run.

Never rely on measurements like this one and better use browser dev tools, they're great!

Collapse
 
3sanket3 profile image
Sanket Patel • Edited

Yes, I agree this is not something that can measure the performance of whole app, but as @dimpiax rightly said, can be useful just to check time consumption of the piece of code quickly.

I also appreciate the point you mentioned about the browser dev tool. I tried it after @bgadrian mentioned in a comment above. But in my brief experiment I found it with too much high level info, may be I need to check the official tutorials to get better idea. Would love to know if you have any reference. Thanks!

Collapse
 
dimpiax profile image
Dmytro Pylypenko

In case of unit tests measurement โ€“ current approach is perfect.

Collapse
 
bgadrian profile image
Adrian B.G.

Not really, is better to use a tool like benchmark.js and wrap your functions there, this way you avoid polluting your code and keep it away from the production bundles.

Thread Thread
 
dimpiax profile image
Dmytro Pylypenko

It depends on skills of developer, if he cannot write vanilla simple functions and doesn't know how to organize architecture and behavior of application, which produces polluting โ€“ then developer starts to use 3rd party libraries for trivial purposes.
If developer is skilled โ€“ it's enough to wrap using native functions, like console.time and console.timeEnd.

For example:

const measure = (label, closure) => { 
    console.time(label); 
    closure(); 
    console.timeEnd(label); 
}

measure('one', () => { 
    Array.from(Array(10000), (_, i) => i).map(v => Math.random(v)); 
})
Thread Thread
 
varoman profile image
varo manukyan • Edited

Please note, every time you re-run it will produce completely different results, so you can't event say how long it will take a particular function to run.

Unlike console.time(), benchmark allows you to run you suits lots of times, giving your more correct average results.

Or you can test your units with jsperf.com/

Thread Thread
 
dimpiax profile image
Dmytro Pylypenko

Of course, because processor allocates resources differently.
When we talk about measurement for unit tests or for performance function โ€“ time is the range of allowed min/max.

Thread Thread
 
bgadrian profile image
Adrian B.G.

I agree, the dev must know what a framework does, but framework or vanilla, the LOC used to benchmark (like performance or console) would be better to be in separate .js files, which are not bundled into the product.