pperf (but not really)

You're in a forest. What do you do?

look

You see a computing machine.

look at computing machine

The computing machine looks back

run

There is no running from the machine. You're not fast enough.


Welcome to the performance chapter! In this lil snip we'll get you up to speed with the ✨ Performance API! ✨.

The perf API (as us kids call it) might have a funny ring to it. It's not quite an API that you can call to make things more performant. It's an API that helps you measure performance.

As some old person once said: "If you can't measure it, you can't improve it". I think Buzzfeed debunked this at some point, but it sounds catchy so we'll roll with it.

The perf API is available in most modern browsers, and in the 8.x or higher Node versions. There are slight differences between the two APIs, but they can be reasoned about similarly. In this exercise we'll focus on the browser, because of better integration with devtools.


The perf API has a few methods:

Exercise 1

Hint


We should now have a cool baseline. When you click a button it performs a small computation, and measures how long it took. Nice!

Now, inside the browser there's a mechanism called the performance entry buffer. It holds all performance entries, and is usually capped at around 200 entries. Once you go over that number, performance can no longer be measure. That's not great. So let's clean up our marks and measures as we go along.

Exercise 2


Creaing performance observers isn't necessarily the cleanest API. There's a good amount of things you need to remember. Let's create a module that makes this a little simpler. The API should be:

var onPerf = require('./on-performance')

onPerf(function (entry) {
  console.log(entry.name + ': ' + entry.duration + 'ms')
})

Exercise 3


This is pretty cool. But one problem is that if you create multiple listeners, it might not get all events, because we're cleaning them up. The solution is to share the emitter mechanism through a global (e.g. window), and allow multiple listeners to be attached.

Exercise 4

Note

This might throw off certain analytics vendors, as they will try and do something similar. If you're going to be using the things you just learned in a production environment, it might be useful to do a little research to figure out how to play nicely with analytics vendors, as they might assume that nobody else is looking at the performance API.

See Also

Edit on GitHub Status: offline