How to pass metadata to performance.measure

performance.measure is a useful API in JavaScript. That’s for measuring duration time between any two points of code. And it can be used on Browser and Node.js. You don’t have to build a custom tracker with Date.

That’s simple, standard, doesn’t pollute the scope, and you can get a higher precision value than Date.now(). That means you can collect metrics even if it takes under 1ms.

But when you try to introduce performance.measure() to collect performance metrics, you might face the problem. The problem is you are not able to pass any additional params to the API. In many cases, the duration time depends on the context (argument, length of Array, items of Map, memory usage in the process, number of DB records, etc.). But it doesn’t provide any argument to pass additional params. That’s not useful. So I’ll put some tips and information for the person who wants to add additional params to performance.measure.

User Timing Level 3 will fix the problem

User Timing Level 3 is a Working Draft(at 18 August 2020) specification by W3C. In that spec, we can find the additional optional argument detail for each method and an example of the option:

The type definition of detail is any! You can pass any values here! Yay! But right now it doesn’t work on major browsers and Node.js except Chrome. We should be patient until the spec will be RC.

How can we solve the problem right now?

For now, the detail option doesn’t work. So we need to pass some metadata somehow. Let you show a workaround for the problem.

The first argument of performance.measure() expects the type of string. So we can pass a JSON serialized string as an argument. And parse it in the callback of PerformanceObserver to restore the metadata. I don’t think it’s the best approach, it’s just a workaround. You’re able to collect performance metrics with some metadata.

Stay safe! Happy coding.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Leko

Leko

Software developer. I love JavaScript and TypeScript.