var string = "Hello world!";
var regex = /Hello/;
regex.test(string);
string.includes("Hello");
string.match("Hello");
"Hello" == string.slice(0, "Hello".length);
string.slice(0, 5) === "Hello"
string.startsWith("Hello")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegEx.test | |
String.includes | |
String.match | |
== | |
=== known length | |
startsWith |
Test name | Executions per second |
---|---|
RegEx.test | 52750816.0 Ops/sec |
String.includes | 179769120.0 Ops/sec |
String.match | 10607238.0 Ops/sec |
== | 185725104.0 Ops/sec |
=== known length | 179321760.0 Ops/sec |
startsWith | 92484744.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of six different approaches for testing if a string contains or matches a certain pattern:
regex.test(string)
string.includes("Hello")
string.match("Hello")
"Hello" == string.slice(0, "Hello".length)
string.slice(0, 5) === "Hello"
string.startsWith("Hello")
Options Compared
Each option is compared to measure its performance:
regex.test(string)
uses a regular expression engine to test if the string contains the pattern.string.includes("Hello")
uses a simple substring search with the includes()
method.string.match("Hello")
also uses a regular expression engine, but it's less efficient than regex.test()
."Hello" == string.slice(0, "Hello".length)
compares the sliced string with a hardcoded string using the loose equality operator (==
).string.slice(0, 5) === "Hello"
compares the sliced string with a hardcoded string using the strict equality operator (===
).string.startsWith("Hello")
uses a simple check for the starting index of the pattern.Pros and Cons
Here's a brief summary of each option:
regex.test()
or string.match()
, as it only checks for substring presence, not exact matches.regex.test()
, but less efficient due to the specific syntax.===
).regex.test()
or string.match()
, and may be slower due to the overhead of the comparison.Libraries and Special Features
None of these options require a specific library or special feature in JavaScript.
However, if you're interested in exploring alternative approaches, you can consider using:
RegExp
objects with the test()
methodString.prototype.includes()
and String.prototype.match()
String.prototype.startsWith()
(available in modern browsers)Keep in mind that these alternatives may not be as efficient or accurate as the original options.
Benchmark Results
The benchmark results show that:
string.startsWith("Hello")
is the fastest option, followed closely by regex.test(string)
and string.includes("Hello")
.I hope this explanation helps you understand the benchmark and its results!