Benchmark, performance.now. Modern browsers deliver ever-increasing performance to JavaScript programs. Advanced optimizations are done on code.
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 two 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 title bar of the web browser (which is often a tab bar).
// The performance.now method measures time in milliseconds.
var time1 = performance.now();
// Perform the benchmark.
for (var i = 0; i < 100000; i++) {
var test = document.createElement("span");
test.id = "test";
}
// Get end time and compute elapsed milliseconds.
var time2 = performance.now();
var elapsed = time2 - time1;
// Write elapsed time to browser title bar.
document.title = elapsed + " ms";43.48 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.
A summary. How much benchmarking should we do? Probably the more things we benchmark, the faster our code will become. But higher-level concerns, like page weight, 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.