var string = "Hello world!";
var regex = new RegExp('hello', 'i');;
regex.test(string);
string.toUpperCase().includes("hello".toUpperCase());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegEx.test | |
String.includes |
Test name | Executions per second |
---|---|
RegEx.test | 10897245.0 Ops/sec |
String.includes | 13406610.0 Ops/sec |
Let's break down what is being tested in this benchmark.
What is being compared:
The benchmark compares the performance of two approaches:
String.includes
with case insensitive: This approach uses the includes()
method to search for the substring "hello"
within the string "Hello world!"
. The i
flag at the end of the regular expression tells JavaScript to perform a case-insensitive match.RegExp.test
: This approach uses the test()
method with a regular expression to search for the substring "hello"
within the string "Hello world!"
. The regular expression is created using the new RegExp('hello', 'i')
constructor, which also performs a case-insensitive match.Pros and cons of each approach:
String.includes
: This approach has the advantage of being more straightforward and easier to read. It's also less error-prone since it doesn't require manual management of the regular expression flags.includes()
might be slower than a custom implementation using RegExp.test
.RegExp.test
: This approach provides better performance since it can take advantage of the optimized C++ engine used by V8 (the JavaScript engine in Chrome).Library used:
There is no specific library mentioned in the benchmark definition. However, RegExp
is a built-in JavaScript class that provides support for working with regular expressions.
Special JS feature or syntax:
There are no special features or syntaxes being tested in this benchmark.
Other alternatives:
If you wanted to compare other approaches, here are some alternatives:
String.indexOf()
: Similar to includes()
, but returns the index of the first match instead of a boolean value.startsWith()
or endsWith()
: These methods can be used in combination with toLowerCase()
or toUpperCase()
to achieve case-insensitive matching.'gi'
flag for global and insensitive matching.Keep in mind that these alternatives may have different performance characteristics compared to the approaches being tested.