function getReConstructor() {
return new RegExp('^[0-9a-fA-F]{24}$');
}
function getReFactory() {
return RegExp('^[0-9a-fA-F]{24}$');
}
function getReLiteral() {
return /^[0-9a-fA-F]{24}$/;
}
var premadeLiteral = /^[0-9a-fA-F]{24}$/;
function getRePremadeLiteral() {
return premadeLiteral;
}
getReConstructor().test('132abc67219f019afe12901a')
getReFactory().test('132abc67219f019afe12901a')
getReLiteral().test('132abc67219f019afe12901a')
getRePremadeLiteral().test('132abc67219f019afe12901a')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new RegExp() | |
RegExp() factory | |
Literal | |
Literal premade |
Test name | Executions per second |
---|---|
new RegExp() | 2351970.2 Ops/sec |
RegExp() factory | 2373543.8 Ops/sec |
Literal | 5920105.0 Ops/sec |
Literal premade | 4217609.5 Ops/sec |
I'll break down the provided benchmark definition and test cases, explaining what's being tested, the pros and cons of different approaches, and other considerations.
Benchmark Definition
The benchmark measures the performance of three ways to create or use regular expressions (RegEx) in JavaScript:
RegExp
constructor.getReFactory
) to create a new RegEx object.Prepared Functions
The benchmark provides four functions:
getReConstructor
: Creates a new RegEx object using the RegExp
constructor with a predefined pattern.getReFactory
: Returns a RegEx object created using the RegExp
constructor with a predefined pattern ( identical to getReConstructor
, but explicitly documented as a factory method).getReLiteral
: Returns a raw string literal defining the RegEx pattern.getRePremadeLiteral
: Returns an already compiled and cached RegEx object, which is equivalent to using a literal RegEx.Individual Test Cases
Each test case measures the performance of one specific scenario:
getReConstructor().test('132abc67219f019afe12901a')
.getReFactory().test('132abc67219f019afe12901a')
.getReLiteral().test('132abc67219f019afe12901a')
.getRePremadeLiteral().test('132abc67219f019afe12901a')
.Pros and Cons
Here's a brief analysis of each approach:
new RegExp()
constructor, but with added documentation clarity.Other Considerations
getRePremadeLiteral
) to optimize performance. This approach can reduce overhead by reusing an already compiled RegEx.^[0-9a-fA-F]{24}$
), which may affect performance due to increased processing time.Alternatives
Other alternatives for creating or using RegEx in JavaScript include:
match()
, search()
, or replace()
, which can be faster but are limited in their functionality.regex-optimize
or regex-cache
.RegEx.prototype.test()
or String.prototype.matchAll()
, which can improve performance and readability.In summary, the benchmark measures the performance of three approaches to creating or using RegEx in JavaScript: new RegExp()
constructor, literal RegEx, and factory method. Each approach has its pros and cons, and the benchmark considers cache reuse, pattern complexity, and other factors to optimize performance.