Created
January 29, 2021 07:53
-
-
Save YoshiTheChinchilla/bc6177cd5b8c6114ed5a08d98c27248d to your computer and use it in GitHub Desktop.
Benchmarking RegExp and String procedure in JavaScript https://github.com/bestiejs/benchmark.js
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
// $ npm i --save benchmark microtime | |
const Benchmark = require('benchmark') | |
const suite = new Benchmark.Suite | |
const str = 'E0123' | |
const compiledRegex = new RegExp(/E\d{4}/) | |
suite | |
.add('RegExp#match', function() { | |
const matched = str.match(/E\d+/) | |
return matched[0] && matched[0].length === 4 | |
}) | |
.add('RegExp#match(4-lengthed)', function() { | |
const matched = str.match(/E\d{4}/) | |
return Boolean(matched[0]) | |
}) | |
.add('Compiled RegExp#match(4-lengthed)', function() { | |
const matched = str.match(compiledRegex) | |
return Boolean(matched[0]) | |
}) | |
.add('String procedure', function() { | |
if(!str.startsWith('E')) { | |
return false | |
} | |
const sub = str.substring(1, 5) | |
if(sub.length != 4) { | |
return false | |
} | |
const parsed = parseInt(sub, 10); | |
if (isNaN(parsed)) { return false; } | |
return true | |
}) | |
.on('cycle', function(event) { | |
console.log(String(event.target)) | |
}) | |
.on('complete', function() { | |
console.log('Fastest is ' + this.filter('fastest').map('name')) | |
}) | |
.run({ 'async': true }); |
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
RegExp#match x 14,625,424 ops/sec ±5.23% (76 runs sampled) | |
RegExp#match(4-lengthed) x 16,273,825 ops/sec ±1.97% (90 runs sampled) | |
Compiled RegExp#match(4-lengthed) x 17,805,892 ops/sec ±4.04% (88 runs sampled) | |
String procedure x 13,121,956 ops/sec ±1.17% (87 runs sampled) | |
Fastest is Compiled RegExp#match(4-lengthed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment