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:
one year ago
User agent:
Mozilla/5.0 (Linux; Android 13; SM-G780G) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36 EdgA/108.0.1462.54
Test name
Executions per second
constructor
799634.8 Ops/sec
memoize
1355083.5 Ops/sec
common boilerplate
1731009.5 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