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 | 121484672.0 Ops/sec |
Includes | 131672744.0 Ops/sec |
In the provided benchmark definition, two methods for checking the presence of a substring in a string in JavaScript are compared: indexOf
and includes
.
indexOf
string.indexOf('tempor') !== -1
indexOf
method is used to determine the index position of the substring 'tempor' within the larger string. If the substring is found, it returns the index (0 or greater); if not found, it returns -1. The comparison to -1 checks for the presence of the substring.includes
string.includes('tempor')
includes
method is a more modern and straightforward way to check for the presence of a substring. It returns true if the substring is found in the string and false otherwise.Pros:
Cons:
includes
, as the logic for presence check requires an additional comparison (!== -1
).Pros:
Cons:
The benchmark results show that the includes
method outperforms the indexOf
method in terms of execution speed, with 131,672,744 executions per second compared to 121,484,672 executions per second for indexOf
. This suggests that includes
is not only more readable but also more efficient in this test scenario.
Performance Context: While the benchmark indicates includes
is faster in this particular case, performance can vary depending on the string's size and the runtime environment. In some contexts, indexOf
might be optimized differently, so testing in the specific use case is advisable.
Legacy Support: If supporting older browsers is a priority, indexOf
might be the better choice, while transpilation tools (like Babel) could be used to bring includes
functionality to older environments.
/tempor/.test(string)
), which might provide powerful pattern matching at the cost of performance.In summary, this benchmark compares two methods of substring searching in JavaScript, with implications for performance, readability, and compatibility, important factors that software engineers must consider when choosing between them.