Skip to content

Instantly share code, notes, and snippets.

@13protons
Forked from dai-shi/benchmark-startswith.js
Last active December 17, 2017 19:09
Show Gist options
  • Save 13protons/800d71eeda40ab47830da92b3211c6eb to your computer and use it in GitHub Desktop.
Save 13protons/800d71eeda40ab47830da92b3211c6eb to your computer and use it in GitHub Desktop.
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('startsWith', function() {
var r1 = (s.startsWith("test", 0) === 0);
var r2 = (s.startsWith("not there", 0) === 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
});
@13protons
Copy link
Author

Update now that node actually does support String.startsWith

indexOf x 90,718 ops/sec ±3.66% (83 runs sampled)
startsWith x 7,861,168 ops/sec ±1.22% (84 runs sampled)
lastIndexOf x 11,840,350 ops/sec ±0.88% (88 runs sampled)
substring x 9,315,588 ops/sec ±1.24% (86 runs sampled)
slice x 9,203,373 ops/sec ±1.03% (91 runs sampled)
regex x 6,537,699 ops/sec ±1.25% (90 runs sampled)
compiled regex x 6,862,322 ops/sec ±1.25% (88 runs sampled)

substring and slice are about the same, and clearly the fastest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment