Regexp creation vs memoization
I need to obtain and use regexps from a string. I'm testing wether I should cache regexps or just construct them on demand.
Date tested:
3 years ago
User agent:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Test name
Executions per second
constructor
1395480.0 Ops/sec
memoize
1850499.0 Ops/sec
common boilerplate
2379147.0 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
var cache = {} const regexps = [ /^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$/, /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|622((12[6-9]|1[3-9][0-9])|([2-8][0-9][0-9])|(9(([0-1][0-9])|(2[0-5]))))[0-9]{10}|64[4-9][0-9]{13}|65[0-9]{14}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})*$/, /[^@/]+@[^@/]+/, /\\s+/, /[^a-zA-Z0-9]/, /^$/, /^[1-9]+[0-9]*$/, /(^\d*\.?\d*[0-9]+\d*$)|(^[0-9]+\d*\.\d*$)/, /^-?[0-9]{0,2}(\.[0-9]{1,2})?$|^-?(100)(\.[0]{1,2})?$/, ] const sources = regexps.map(r => r.source) regexps.forEach(r => { cache[r.source] = r }) const n = sources.length const floor = Math.floor const random = Math.random function getRandomSource () { return sources[floor(random() * n)] }
Tests:
constructor
window.result = new RegExp(getRandomSource())
memoize
window.result = cache[getRandomSource()]
common boilerplate
window.result = getRandomSource()
Open this result on MeasureThat.net