Skip to content

Instantly share code, notes, and snippets.

@dai-shi
Created November 10, 2013 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dai-shi/7394062 to your computer and use it in GitHub Desktop.
Save dai-shi/7394062 to your computer and use it in GitHub Desktop.
benchmark various regexp syntax.
var Benchmark = require('benchmark');
Benchmark.prototype.setup = function() {
l = 100000;
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtestyyyyyyyyyyyyyyyyyyyyy';
re1 = /te[xs]t/;
re2 = new RegExp('te[xs]t');
re3 = new RegExp('te[xs]t');
re3.compile();
re4 = new RegExp();
re4.compile('te[xs]t');
};
var suite = new Benchmark.Suite();
// add tests
suite.add('inline regex', function() {
for (var i = 0; i < l; i++) {
var r = /te[xs]t/.test(s);
}
})
.add('normal regex', function() {
for (var i = 0; i < l; i++) {
var r = re1.test(s);
}
})
.add('object regex', function() {
for (var i = 0; i < l; i++) {
var r = re2.test(s);
}
})
.add('compiled regex [1]', function() {
for (var i = 0; i < l; i++) {
var r = re3.test(s);
}
})
.add('compiled regex [2]', function() {
for (var i = 0; i < l; i++) {
var r = re4.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
});
@dai-shi
Copy link
Author

dai-shi commented Nov 10, 2013

$ node -v
v0.10.15
$ node ./benchmark-regex-compile.js
inline regex x 107 ops/sec ±0.46% (80 runs sampled)
normal regex x 114 ops/sec ±0.76% (75 runs sampled)
object regex x 114 ops/sec ±0.74% (75 runs sampled)
compiled regex [1] x 187 ops/sec ±1.72% (81 runs sampled)
compiled regex [2] x 114 ops/sec ±0.73% (75 runs sampled)
Fastest is compiled regex [1]

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