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.
This is a benchmark harness page. It contains 2 calls to performance.now
—these measure the current time in milliseconds.
performance.now
once before, and once after, the code we wish to benchmark.// 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
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.
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.