How to Measure Performance in JavaScript


In this article, we’ll go through a few different ways to measure the time it takes to run code blocks or programs in JavaScript.

Using console.time and console.timeEnd

We can wrap a function inside console.time() and console.timeEnd() to print the number of milliseconds it takes to execute that function.

console.time();
someFunction();
console.timeEnd();
default: 1.8374628374ms

We can pass in labels as parameters, which will allow console.time() and console.timeEnd() to distinguish multiple tests. Note that the labels must be matching.

console.time("func1"); // First function
oneFunction();
console.timeEnd("func1");
console.time("func2"); // Second function
twoFunction();
console.timeEnd("func2");
func1: 1.9483758274ms
func2: 2.9283746182ms

I personally use this function to automatically log tests. It prints the time it takes to the run the input function ten million times (this number can be changed in the third parameter).

function runTest(fn, name, n = 10000000) {
    console.time(name);
    for(let i = 0; i < n; i++) { fn(); }
    console.timeEnd(name);
}

I used this method in my article comparing different methods of iterating through JSON objects.

Using performance.now

By itself, performance.now() will return the time since the page loaded.

let t0 = performance.now();
someFunction();
let t1 = performance.now();
let time = t1 - t0; // in ms

We can use the following function to automatically log tests.

function runTest(fn, name, n = 10000000) {
    let t0 = performance.now();
    for(let i = 0; i < n; i++) { fn(); }
    let t1 = performance.now();
    console.log(`${name}: ${t1 - t0}ms`);
}

However, the current state of performance.now() is stated as follows by Mozilla:

The timestamp is not actually high-resolution. To mitigate security threats such as Spectre, browsers currently round the result to varying degrees. (Firefox started rounding to 2 milliseconds in Firefox 59.) Some browsers may also slightly randomize the timestamp. The precision may improve again in future releases; browser developers are still investigating these timing attacks and how best to mitigate them.

Using online performance tests

These tools allow you to run benchmarks on your code snippets and can serve as an alternative to the two methods above.

It’ll also be helpful to read about the pitfalls of JavaScript benchmarking if you’re looking to do real-world tests.