<!--your preparation HTML code goes here-->
let string = 'hello123'
let f = /(hello|hi)123/
let n = /(?:hello|hi)123/
string.match(f)
string.match(n)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
capturing | |
non capturing |
Test name | Executions per second |
---|---|
capturing | 15344823.0 Ops/sec |
non capturing | 16613423.0 Ops/sec |
This benchmark compares the performance of two types of regular expressions in JavaScript: capturing and non-capturing groups. Both types of regex are commonly used for pattern matching in strings, but they serve slightly different purposes.
let string = 'hello123';
let f = /(hello|hi)123/; // Capturing regex
let n = /(?:hello|hi)123/; // Non-capturing regex
Here, the benchmark initializes a test string, string
, with the value 'hello123'
. It also defines two regular expressions:
f
which uses capturing groups /(hello|hi)123/
n
which uses non-capturing groups /(?:hello|hi)123/
Capturing Test Case:
string.match(f)
hello
or hi
in string
. Capturing groups are useful when you need to extract and use the matched portions later.Non-Capturing Test Case:
string.match(n)
The benchmark results indicate the number of executions per second for both test cases:
The non-capturing regex performed faster than the capturing regex. This is generally expected, as non-capturing groups require less overhead since they do not need to store matches.
Using Different Regex Engines: Various JavaScript libraries offer different regex engines (like XRegExp) that may provide enhanced functionality. These libraries allow for more complex operations, such as named capturing groups, but may trade off some performance.
String Methods: For simple substring searches, methods like String.includes()
, String.startsWith()
, or String.endsWith()
may provide clarity and improved performance when regular expressions are not required.
Custom Logic: In some use cases, manual string manipulation combined with logical conditions might outperform even optimized regex, particularly for predictable formats.
This benchmark highlights the performance characteristics of capturing vs. non-capturing regex in JavaScript, guiding engineers in their decision-making process when using regular expressions for pattern matching.