window.myString = 'a looooooong string who knows how Long'
window.regexpI = new RegExp('long', 'i');
window.regexp = new RegExp('long');
myString.toLowerCase().indexOf('long') !== -1
myString.toLowerCase().includes('long')
myString.toLowerCase().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 | 16244643.0 Ops/sec |
includes | 16124331.0 Ops/sec |
regex case sensi | 5621777.5 Ops/sec |
regex case insensi | 6331179.5 Ops/sec |
Let's dive into the explanation of what's being tested in this benchmark.
What is being tested?
The benchmark measures the performance of three different string searching methods:
.indexOf()
includes()
match()
with and without case sensitivity (i.e., using a regular expression with an "i" flag for case-insensitive matching)These tests are designed to find the fastest way to search for a specific substring within a large, prepared string.
Options compared:
.indexOf()
: This method returns the index of the first occurrence of the specified substring. If the substring is not found, it returns -1.includes()
: This method returns a boolean value indicating whether the specified substring exists in the string.match()
with and without case sensitivity: The "i" flag is used to make the regular expression case-insensitive.Pros and cons of each approach:
.indexOf()
:includes()
:.indexOf()
, as it returns a boolean value instead of an index..indexOf()
for large strings, since it needs to iterate over the entire string.match()
with and without case sensitivity:.indexOf()
due to the overhead of regular expression evaluation.Library usage:
None of the benchmark tests rely on any external libraries. The prepared string and regular expressions are hardcoded in the script preparation code.
Special JS features or syntax:
Other alternatives:
If you wanted to test these benchmarks differently, here are some alternative approaches:
Keep in mind that these alternatives might not be directly comparable to the original benchmark tests, and you'd need to modify the test cases accordingly.