performance.now (Benchmark)Perform a benchmark on a for-loop and measure the elapsed time with performance.now.
This page was last reviewed on Dec 13, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (edit).
© 2007-2024 Sam Allen.