var string = "Hello world!";
string.indexOf("Hello") !== -1
string.includes("Hello");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
String.includes |
Test name | Executions per second |
---|---|
IndexOf | 17350246.0 Ops/sec |
String.includes | 17325752.0 Ops/sec |
Let's break down the provided benchmark and its components.
Benchmark Definition
The benchmark is comparing two string methods: indexOf
and includes
. The purpose of this benchmark is to determine which method is faster for searching for a substring within a larger string.
Script Preparation Code
The script preparation code is simply creating a variable string
with the value "Hello world!"
. This sets up the initial string that will be used in the tests.
Html Preparation Code
There is no HTML preparation code provided, which suggests that this benchmark is focused solely on JavaScript performance and does not involve any additional web page rendering or DOM manipulation.
Test Cases
The test cases are defined within a nested object:
[
{
"Benchmark Definition": "string.indexOf(\"Hello\") !== -1",
"Test Name": "IndexOf"
},
{
"Benchmark Definition": "string.includes(\"Hello\");",
"Test Name": "String.includes"
}
]
These test cases are identical to the benchmark definition, with the first test case checking if indexOf
returns a truthy value for searching for "Hello"
within the initial string, and the second test case checking if includes
returns a truthy value for doing the same.
Pros and Cons of Different Approaches
There are two main approaches being compared here:
indexOf
: This method searches for the specified substring from left to right and returns the index of the first occurrence, or -1 if it's not found. This approach can be slower than includes
because it involves searching the entire string.includes
: This method simply checks if the specified substring is a part of the original string, returning a boolean value indicating whether it exists. This approach is generally faster than indexOf
because it only needs to check for existence, rather than finding the exact index.Pros and Cons
indexOf
:includes
:Library and Purpose
There is no library being used in this benchmark. It appears that these methods are built-in to JavaScript.
Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax beyond standard ECMAScript functions.
Other Alternatives
If you wanted to explore other string search methods, some alternatives could be:
RegExp
objectlodash.string
which provides optimized string searching methodsHowever, for simple substring searches within JavaScript, using built-in indexOf
and includes
methods remains a suitable choice.