<!--your preparation HTML code goes here-->
var elements = Array.of(1000000).fill(0)
var literalRegexps = elements.map(() => /a/)
var constructedRegexps = elements
literalRegexps.forEach((r) => r.test('aaaa'))
constructedRegexps.forEach((r) => new RegExp('a'.replace(/a/g, 'b')).test('aaaa'))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Literal RegExps | |
Constructed RegExps |
Test name | Executions per second |
---|---|
Literal RegExps | 43989120.0 Ops/sec |
Constructed RegExps | 10458753.0 Ops/sec |
The benchmark described in the provided JSON evaluates the performance difference between two ways of creating regular expressions (RegExps) in JavaScript: using literal syntax and using the constructor function.
Literal Regular Expressions:
/a/
. This approach allows for direct and immediate pattern definition.literalRegexps.forEach((r) => r.test('aaaa'))
literalRegexps
is an array filled with a million instances of the /a/
RegExp.Constructed Regular Expressions:
RegExp
constructor, e.g., new RegExp('a')
. This approach allows for dynamic construction of regex patterns, which can be useful when regex patterns are determined at runtime.constructedRegexps.forEach((r) => new RegExp('a'.replace(/a/g, 'b')).test('aaaa'))
constructedRegexps
is an array of zeros which are intended to represent instances where RegExp is constructed anew in each iteration.Pros:
Cons:
Pros:
Cons:
Memoization: For cases where constructed RegExp patterns are used repeatedly, memoizing the created regex can help. This technique involves storing computed values (in this case, RegExp objects) so they can be reused, minimizing the performance overhead.
Template Literals: For concatenating strings used in regex, template literals can simplify dynamic creation while maintaining performance if they can be combined with precompiled regex patterns.
Performance Profiling: Using performance profiling tools can assist developers in determining the best approach based on their specific scenarios.
In summary, for scenarios where the regex pattern is static, using literal regex will generally offer better performance and code clarity. However, if you require dynamic patterns, consider the overhead of constructing RegExp objects and potential strategies for optimizing performance.