var str = "AB CD EF GH IJ KL";
var needle = "CD";
var regex = /\bCD\b/;
var escapeRegEx = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
str.split(' ').includes(needle);
str.match(escapeRegEx(needle))
str.match(regex)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
str.split.includes | |
regex - create inline | |
regex - create first |
Test name | Executions per second |
---|---|
str.split.includes | 7773167.5 Ops/sec |
regex - create inline | 3112663.0 Ops/sec |
regex - create first | 9836886.0 Ops/sec |
I'd be happy to explain the provided benchmark.
Benchmark Definition
The benchmark is designed to compare three different approaches for testing whether a specific string (needle
) is included in another string (str
):
includes()
method on an array returned by the split()
method, which splits the string into words.match()
method to search for the needle within the original string.escapeRegEx()
function.Options Compared
The three options are compared as follows:
escapeRegEx()
function, which escapes special characters in the needle to create a safe regex pattern. The resulting pattern is then used with the match()
method to search for the needle within the original string./\\bCD\\b/
syntax (explained later). The resulting pattern is then used with the match()
method to search for the needle within the original string.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
escapeRegEx()
) which may add complexity.escapeRegEx()
.Library and Purpose
The escapeRegEx()
function is used to escape special characters in the needle to create a safe regex pattern. This is necessary because some special characters have a specific meaning in regex, such as .
, *
, and ?
. By escaping these characters, the resulting pattern will match only the intended substring.
Special JS Feature or Syntax
The benchmark uses the following JavaScript features:
"var str = \\u201cAB CD EF GH IJ KL\\u201d;"
line to create a string with escaped quotes."var escapeRegEx = (string) => string.replace(/[.*+?^${}()|[\\]\\\\]/g, \\\\$&')"
line to define the escapeRegEx()
function.Other Alternatives
If you're interested in exploring alternative approaches or optimizations, here are a few ideas:
String.prototype.includes()
instead of Array.prototype.includes()
: This might be slightly faster for very large strings.g
, i
) to see if they improve performance.split(' ')
, you could try str.split('CD')
or another approach.Keep in mind that these are just suggestions, and the best approach will depend on your specific use case and performance requirements.