Benchmarks in JavaScript
Speeding up page load times is a good way to decrease bounce rates and increase customer satisfaction. And if you’re using JavaScript in your server-side architecture, speed will become increasingly important. So you might be tempted to write your own benchmarking code when puzzling over a tricky performance issue. Fortunately there are quite a few JavaScript benchmarking libraries out there.
Unit Tests
If you’re writing unit tests you should get some benchmark information. Most libraries automatically benchmark tests — unittest.js includes a benchmark method. You could use this outside of tests for some foresnic analysis.
JavaScript Benchmark
JavaScript Benchmark is a nice little library that features:
- ASCII-friendly output that’s great for server-side JavaScript
- A simple API
- Test suite support
Each benchmark will be run once by default, or you can specify a value:
suite('Iteration', 50000, function() {
array = [1,2,3,4,5,6,7,8,9];
benchmark('for', function() {
for (var i = 0; i < array.length; ++i);
});
benchmark('for cached', function() {
for (var i = 0, len = array.length; i < len; ++i);
});
benchmark('for in', function() {
for (var i in array);
});
});
This library won’t work in a browser due to the use of the print() function, but all you need to do is supply your own. Something like this will do:
function print(message) {
document.getElementById('log').innerHTML += message + "\n";
}
I’ve put a full example up here: benchmarks.html
BenchmarkBuddy
BenchmarkBuddy is inspired by the RunSingleBenchmark from the V8 source. Here’s one of the author’s examples:
alert(BenchmarkBuddy.run(Math.random));
Benchmark.js
Benchmark.js is based on Ruby’s benchmark library. It’s still a work in progress and isn’t currently console-friendly, but when it works it will look like this:
Benchmark.benchmark(function() {
for (i = 0; i < 10000000; i++) { }
});