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('commodo') > -1
string.includes('commodo')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
includes |
Test name | Executions per second |
---|---|
indexOf | 13742652.0 Ops/sec |
includes | 13894137.0 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Description
The benchmark is designed to compare two different methods for searching a specific substring within a string: String.indexOf()
and String.includes()
. The focus is on determining which method performs better in terms of execution speed.
Options Compared
Two main options are being compared:
string.indexOf('commodo') > -1
: This uses the traditional indexOf()
method, which returns the index of the first occurrence of the specified substring. If the substring is not found, it returns -1
.string.includes('commodo')
: This uses the newer includes()
method, introduced in ECMAScript 2015 (ES6), which returns a boolean value indicating whether the string includes the specified substring.Pros and Cons
indexOf()
Method:
Pros:
Cons:
includes()
Method:
Pros:
indexOf()
Cons:
Library Usage
In the benchmark, both tests use the string
variable, which is not explicitly mentioned in the JSON. However, we can assume that this string is created using a JavaScript engine or environment that supports string manipulation.
Special JS Feature/Syntax
The includes()
method uses a new syntax introduced in ECMAScript 2015 (ES6), specifically called "inclusive" matching, which includes the search term itself in the match. This is why string.includes('commodo')
returns true
, even if 'commodo' appears only at the end of the string.
Other Alternatives
For the indexOf()
method, alternative approaches might include:
For the includes()
method, other alternatives could be:
some()
or every()
methods with a callback functionString.prototype.includes.call()
However, it's worth noting that these alternative approaches might not offer significant performance benefits over the built-in indexOf()
and includes()
methods.
Benchmark Preparation Code
The provided script preparation code creates a string variable string
with some sample text. This is likely intended to demonstrate the benchmark scenario without affecting the test results.
Overall, the benchmark provides a useful comparison between two JavaScript methods for searching substrings within strings. By understanding the pros and cons of each approach, developers can make informed decisions about when to use indexOf()
versus includes()
.