Performance has always played a crucial part in software. On the web, performance is even more important as our users can easily change website and visit one of our competitors if we offer them slow pages. As professional web developers, we have to take this issue into account. A lot of old web performance optimization best practices, such as minimizing requests, using a CDN and not writing rendering blocking code, still apply today. However, as more and more web apps are using JavaScript, it’s important to verify that our code is fast.
Suppose that you have a working function but you suspect it’s not as fast as it could be, and you have a plan to improve it. How do you prove this assumption? What’s the best practice for testing the performance of JavaScript functions today? Generally, the best way to achieve this task is to use the built-in performance.now()
function and measure the time before and after your function executes.
In this article we’ll discuss how to measure code execution time and techniques to avoid some common pitfalls.
The High Resolution Time API offers a function, named now()
that returns a DOMHighResTimeStamp
object. It's a floating point number that reflects the current time in milliseconds accurate to a thousandth of a millisecond
. Individually, the number doesn’t add much value to your analysis, but a difference between two such numbers gives an accurate description of how much time has passed.
In addition to the fact that it is more accurate than the built-in Date
object, it's also “monotonic”. That means, in simple terms, that it’s not affected by the system (e.g. your laptop OS) periodically correcting the system time. In even simpler terms, defining two instances of Date
and calculating the difference isn’t representative of the time that has passed.
The mathematical definition of “monotonic” is (of a function or quantity) varying in such a way that it either never decreases or never increases
.
Another way of explaining it, is by trying to imagine using it around the times of the year when the clocks go forward or go back. For example, when the clocks in your country all agree to skip an hour for the sake of maximizing daytime sunshine. If you were to make a Date
instance before clocks go back an hour, and another Date
instance afterwards, looking at the difference it would say something like “1 hour and 3 seconds and 123 milliseconds”. With two instances of performance.now()
the difference would be “3 seconds 123 milliseconds and 456789 thousands of a millisecond”.
In this section, I won't cover this API in detail. So if you want to learn more about it and see some example of its use, I suggest you to read the article Discovering the High Resolution Time API.
Continue reading %Measuring JavaScript Functions’ Performance%
by Peter Bengtsson via SitePoint