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')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes |
Test name | Executions per second |
---|---|
IndexOf | 261025296.0 Ops/sec |
Includes | 252968304.0 Ops/sec |
The benchmark you've provided compares two JavaScript methods for searching a substring within a string: indexOf
and includes
. This comparison is essential for understanding their performance characteristics as well as their usability in coding.
indexOf
Method:
string.indexOf('tempor') !== -1
indexOf
method returns the first index at which a specified substring can be found within the calling string, or -1 if it is not present. In this benchmark, it checks if the index is not equal to -1, which indicates that the substring exists.includes
Method:
string.includes('tempor')
includes
method determines whether one string can be found within another string, returning true
or false
. It is more straightforward than indexOf
, as it directly returns a boolean, hence indicating presence or absence without needing a comparison to -1.indexOf
:Pros:
Cons:
!== -1
) to interpret the result as a boolean.includes
.includes
:Pros:
Cons:
includes
, requiring polyfills or workarounds for full compatibility.indexOf
had approximately 261 million executions per second, while includes
had about 253 million executions per second. This suggests that indexOf
was slightly faster in this scenario, but both methods performed at a very high speed.includes
might be preferred, despite a minor performance hit.RegExp
object. However, they come with their syntax and performance considerations.includes
or any other modern method not present in the environment.In summary, choosing between indexOf
and includes
can depend on the specific requirements of your project regarding performance, compatibility, and readability. Each method has its place in the JavaScript toolbox, and understanding their nuances can help make more informed decisions in software development.