window.myString = 'a looooooong string who knows how Long'
window.regexpI = new RegExp('long', 'i');
window.regexp = new RegExp('long');
myString.toLocaleLowerCase().indexOf('long') !== -1
myString.toLocaleLowerCase().includes('long')
myString.toLocaleLowerCase().match(regexp)
myString.match(regexpI)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.indexOf | |
includes | |
regex case sensi | |
regex case insensi |
Test name | Executions per second |
---|---|
.indexOf | 12517119.0 Ops/sec |
includes | 12475868.0 Ops/sec |
regex case sensi | 5527187.0 Ops/sec |
regex case insensi | 6327572.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The benchmark measures the fastest way to perform string includes (e.g., includes()
, indexOf()
). The script preparation code sets up two variables: myString
and two regular expressions, regexpI
and regexp
. The HTML preparation code is empty.
Options Compared
Three options are compared:
.includes()
: This method returns a boolean value indicating whether the string contains the specified value..indexOf()
: This method returns the index of the first occurrence of the specified value in the string, or -1 if not found.match()
(with and without case sensitivity).Pros and Cons
Here's a brief summary of each option:
.includes()
:.indexOf()
: match()
:i
flag).Special JS Features
The test uses a special JavaScript feature called "regex case sensitivity" (denoted by the i
flag in the RegExp
constructor). The i
flag makes the regular expression engine perform a case-insensitive match. There is no other special JavaScript feature mentioned in this benchmark.
Library Usage
There are no libraries used in this benchmark.
Other Considerations
When choosing between these methods, consider the following:
.includes()
might be the simplest and most efficient choice..indexOf()
might be a better option.match()
might be the way to go.Alternatives
Other alternatives for this benchmark could include:
String.prototype.includes()
method (available in modern browsers) instead of .includes()
String.prototype.indexOf()
method (available in modern browsers) instead of .indexOf()
replace()
or split()
Keep in mind that the best approach will depend on the specific requirements and constraints of your use case.