Home
Node.js
performance.now (Benchmark)
Updated Dec 13, 2023
Dot Net Perls
Benchmark, performance.now. With Node.js, we have an advanced JavaScript compiler to optimize our code. But sometimes it can still help to benchmark methods.
For a developer, it is hard to know what method is the fastest one. For the development of any application, some benchmarks may be needed. Performance.now enables these.
Example benchmark. This is a benchmark harness page. It contains 2 calls to performance.now—these measure the current time in milliseconds.
And We call performance.now once before, and once after, the code we wish to benchmark.
Result We compute the elapsed time and display it in the console window as text output.
// The performance.now method measures time in milliseconds. var time1 = performance.now(); // Perform the benchmark. for (var i = 0; i < 100000; i++) { var test = i / 5; if (test == 0) { console.log("x"); } } // Get end time and compute elapsed milliseconds. var time2 = performance.now(); var elapsed = time2 - time1; // Write elapsed time. console.log(elapsed + " ms");
x 5.908792 ms
Some notes. Different methods may perform slower or faster in different JavaScript engines. This is unavoidable. But the "ideal" JS code probably does well in all modern engines.
Summary. How much benchmarking should we do? Probably the more things we benchmark, the faster our code will become. But other concerns, like download time, are often more important.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen