var brand = "ted baker";
var isTedBaker;
isTedBaker = brand.indexOf("ted baker") !== -1;
isTedBaker = brand.match(/ted\s+baker/i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
match |
Test name | Executions per second |
---|---|
indexOf | 4099011.0 Ops/sec |
match | 3144507.8 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches: indexOf
and match
. Both methods are used to check if a string contains a specific substring.
Options Compared
There are two options being compared:
indexOf
: This method returns the index of the first occurrence of the specified substring in the original string. If the substring is not found, it returns -1.match
: This method returns an array containing all matches if the regular expression pattern is found anywhere in the string. The i
flag at the end of the regex pattern makes the match case-insensitive.Pros and Cons
indexOf
:match
, as it doesn't require creating a regex object or compiling a pattern.match
:indexOf
, especially for simple substring searches.Library/Utility Used
In this benchmark, the match()
function is used in combination with a regex pattern. The regex pattern /ted\\s+baker/i
breaks down as follows:
^
: Matches the start of the string.ted
: Matches the literal substring "ted".\s+
: Matches one or more whitespace characters (spaces, tabs, etc.).baker
: Matches the literal substring "baker".$
: Matches the end of the string.i
: Makes the match case-insensitive.Special JS Feature/Syntax
In this benchmark, the use of the \s+
regex pattern is worth noting. This is a special syntax in JavaScript that matches one or more whitespace characters. It's not specific to any particular browser or version, but rather part of the standard JavaScript regular expression API.
Other Alternatives
If you needed to compare these two approaches for different reasons, some alternative methods could be:
includes()
instead of indexOf
(which is a modern method introduced in ES2019). includes()
would return a boolean indicating whether the string contains the specified substring.replace()
or split()
instead of match
. These methods can be used to perform more complex operations on the string, but might not be as efficient for simple substring searches.Keep in mind that the best approach depends on your specific use case and requirements.