var string = "Hello world!";
var regex = /Hello/g;
regex.test(string);
string.includes("Hello");
string.match("Hello");
string.match(regex);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegEx.test | |
String.includes | |
String.match | |
String.match with regex |
Test name | Executions per second |
---|---|
RegEx.test | 12527297.0 Ops/sec |
String.includes | 30034456.0 Ops/sec |
String.match | 7332567.5 Ops/sec |
String.match with regex | 8451095.0 Ops/sec |
Measuring the performance of different approaches to regular expression matching in JavaScript is an interesting benchmark.
What's being tested:
The provided JSON represents a benchmark that compares four approaches for matching regular expressions (RegEx) against strings:
String.includes()
: A method to check if a substring exists within a string.String.match()
: A method to search for the first occurrence of a pattern in a string and returns an array of matches or null if no match is found.String.match(regex)
: A method that uses a regular expression object as its second argument, which allows for more advanced matching capabilities.The benchmark measures the number of executions per second (ExecutionsPerSecond) for each approach using Chrome 109 on Windows desktop devices.
Options compared:
String.includes()
String.match()
String.match(regex)
with a regular expression objectg
flag) for finding all occurrences of the pattern in the string.String.match(regex)
due to limitations on flags and modifiers.Pros and cons:
String.includes():
String.match():
g
flag).String.includes()
due to the overhead of parsing the regular expression.String.match(regex):
g
flag) out-of-the-box.Library usage:
The benchmark uses native JavaScript methods (String.includes()
, String.match()
), so no libraries are involved in this comparison.
No special JavaScript features or syntax are required for these approaches, making them accessible to a wide range of developers.
Alternatives:
If you want to explore other approaches, consider:
Keep in mind that these alternatives may have different trade-offs in terms of performance, complexity, and flexibility.