var string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
string.indexOf('tempor') > -1
string.includes('tempor')
string.indexOf('tempor') !== -1
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes | |
noteq |
Test name | Executions per second |
---|---|
IndexOf | 16623541.0 Ops/sec |
Includes | 19209692.0 Ops/sec |
noteq | 15800014.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided JSON represents a benchmark that tests two methods for searching a string: indexOf
and includes
. The benchmark aims to compare the performance of these two methods on a specific test case, which is a string containing the word "tempor" within it. We'll explore what options are compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark definition consists of three individual test cases:
IndexOf
: Tests if the index of "tempor" in the string is greater than -1.Includes
: Tests if the string includes the substring "tempor".noteq
: Tests if the index of "tempor" in the string is not equal to -1.Options Compared
The benchmark compares two options:
A) indexOf
method
B) includes
method
Pros and Cons of Each Approach
A) indexOf
Method:
Pros:
indexOf
is a more traditional method for searching a substring in a string.Cons:
B) includes
Method:
Pros:
indexOf
.Cons:
indexOf
.Other Considerations
The benchmark also considers two factors not directly related to the search methods:
Library Usage
There's no explicit library usage mentioned in the benchmark definition. However, it's worth noting that includes
method was introduced as a part of ECMAScript 2020 standard, so it's likely that modern browsers (including Firefox) support this method natively.
Special JS Feature or Syntax
The benchmark uses a special feature: nbsp
characters are used in the string to introduce non-breaking spaces. However, this is not explicitly mentioned in the JSON and can be considered as a minor detail.
Alternatives
Other alternatives for searching a substring in a string include:
RegExp
)However, the indexOf
and includes
methods are more straightforward and efficient approaches for this specific use case.