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)]
}
window.result = new RegExp(getRandomSource())
window.result = cache[getRandomSource()]
window.result = getRandomSource()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
constructor | |
memoize | |
common boilerplate |
Test name | Executions per second |
---|---|
constructor | 799634.8 Ops/sec |
memoize | 1355083.5 Ops/sec |
common boilerplate | 1731009.5 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The test compares two approaches to creating regular expressions (regexps) in JavaScript:
cache
) and reuses them instead of recreating them from scratch.Options Compared
The two options being compared are:
Pros and Cons of Each Approach
Pros:
Cons:
Pros:
Cons:
Library Used
In this benchmark, no external libraries are used. The regexps are defined directly in the JavaScript code.
Special JS Feature/Syntax (None)
There are no special JavaScript features or syntaxes being tested in this benchmark.
Other Considerations
When deciding between these two approaches, consider the following:
Alternatives
Other approaches to creating regexps in JavaScript include: