benchmark of String.startsWith equivalents in Node.js
var Benchmark = require('benchmark');
Benchmark.prototype.setup = function() {
a = ["test"];
for (var i = 0; i < 10000; i++) {
a.push("some other stuff");
}
s = a.join();
re1 = new RegExp("^test");
re2 = new RegExp("^not there");
};
var suite = new Benchmark.Suite();
// add tests
suite.add('indexOf', function() {
var r1 = (s.indexOf("test") === 0);
var r2 = (s.indexOf("not there") === 0);
})
.add('lastIndexOf', function() {
var r1 = (s.lastIndexOf("test", 0) === 0);
var r2 = (s.lastIndexOf("not there", 0) === 0);
})
.add('substring', function() {
var r1 = (s.substring(0, "test".length) == "test");
var r2 = (s.substring(0, "not there".length) == "not there");
})
.add('slice', function() {
var r1 = (s.slice(0, "test".length) == "test");
var r2 = (s.slice(0, "not there".length) == "not there");
})
.add('regex', function() {
var r1 = (/^test/).test(s);
var r2 = (/^not there/).test(s);
})
.add('compiled regex', function() {
var r1 = re1.test(s);
var r2 = re2.test(s);
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run({
'async': false
});