Created
November 10, 2013 05:05
-
-
Save dai-shi/7394062 to your computer and use it in GitHub Desktop.
benchmark various regexp syntax.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ 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]