function getReConstructor() {
return new RegExp('^[0-9a-fA-F]{24}$').test('132abc67219f019afe12901a');
}
function getReFactory() {
return RegExp('^[0-9a-fA-F]{24}$').test('132abc67219f019afe12901a');
}
function getReLiteral() {
return /^[0-9a-fA-F]{24}$/.test('132abc67219f019afe12901a');
}
var premadeLiteral = /^[0-9a-fA-F]{24}$/;
function getRePremadeLiteral() {
return premadeLiteral.test('132abc67219f019afe12901a');
}
getReConstructor()
getReFactory()
getReLiteral()
getRePremadeLiteral()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new RegExp() | |
RegExp() factory | |
Literal | |
Literal premade |
Test name | Executions per second |
---|---|
new RegExp() | 5547883.5 Ops/sec |
RegExp() factory | 5522947.0 Ops/sec |
Literal | 13249286.0 Ops/sec |
Literal premade | 9706220.0 Ops/sec |
Let's dive into explaining the benchmark and its various aspects.
Benchmark Description: The benchmark measures the performance of different approaches to create a regular expression (regex) in JavaScript:
new RegExp()
constructorOptions Compared:
new RegExp()
constructor: Creates a new regex object from scratch.Pros and Cons of each approach:
new RegExp()
constructor:Library Used: None
There are no external libraries used in this benchmark.
Special JS Features/Syntax: None mentioned
No special JavaScript features or syntax are used in this benchmark.
Other Alternatives:
RegExp()
: Instead of using the constructor, you can use a regex literal with RegExp()
. For example: var myRegex = RegExp('^[0-9a-fA-F]{24}$');
Benchmark Preparation Code Explanation:
The preparation code defines four functions:
getReConstructor()
: Creates a new regex object using the constructor.getReFactory()
: Creates a regex object using the factory method (RegExp()
).getReLiteral()
: Creates a regex pattern as a string and uses it to test a string.getRePremadeLiteral()
: Uses an existing compiled regex object to test a string.The code also defines two pre-compiled regex objects: premadeLiteral
and its usage in getRePremadeLiteral()
.
Benchmark Result Explanation:
The benchmark results show the execution count per second for each approach on a specific machine. The highest performance is achieved by using the literal regex, followed closely by the premade literal regex. The constructor-based approach has lower performance due to the overhead of creating a new regex object every time it's used.
Keep in mind that these results may vary depending on your specific environment and JavaScript engine.