JavaScript Quick Tip: How To Use The Performance API To Measure Execution Times

JavaScript Quick Tip: How To Use The Performance API To Measure Execution Times

How to measure with greater precision

Measuring execution times of code paths is an essential and fundamental requirement to decide whether code needs refactoring or rewriting because it creates a performance bottleneck.

Until some time ago, you didn't have many choices to measure execution times. This usually lead to the Date API being used by many developers. Date, however, does only provide millisecond precision.

const begin = new Date();
for (let i = 0; i < 100; i++) {
  console.log(i);
}
const end = new Date();

// You'll only get the milliseconds elapsed here
const millisElapsed = end.getTime() - begin.endTime();

No matter what you measure in the way showcased above, you'll never get a more precise result than milliseconds with the Date API.

Enter the Performance API

For quite some time, JavaScript developers have access to the Performance API in both the browser and Node.

It's enough to replace your calls to Date with calls to performance, and you are good to go.

const begin = performance.now();
for (let i = 0; i < 100; i++) {
  console.log(i);
}
const end = performance.now();

// You'll get microseconds elapsed here.
// This is way more precise.
const timeElapsed = end - begin;

One Caveat

Nearly all browsers have reduced the precision of performance.now() again to prevent fingerprinting. This makes this API not the best choice to test your code in the browser.

However, what you can do - and it's the better alternative nevertheless - is to use the performance API in your tests that run on Node. Precision isn't reduced there and perfect to create reports from to protect yourself against performance regressions.

The Whole Tip As An Image

If you like visual content more, or if you want to store it for later, I put all this into one single image for you. I hope you like it!

A picture showcasing the above code

Before You Leave

If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.

I'd love to count you as my ever-growing group of awesome friends!