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 | 6872018.5 Ops/sec |
Includes | 6973593.0 Ops/sec |
Let's dive into the details of this JavaScript microbenchmark.
Benchmark Overview
The benchmark is designed to compare the performance of two string searching methods: indexOf
and includes
. The script preparation code provides a sample string, and the HTML preparation code is not needed in this case. The goal is to measure which method is faster for a specific substring search ("tempor"
).
Options Compared
Two options are compared:
string.indexOf('tempor')>
: This method returns the index of the first occurrence of "tempor"
in the string, or -1
if not found.string.includes('tempor')
: This method returns a boolean value indicating whether the string includes the specified substring.Pros and Cons
indexOf
:includes
:indexOf
for exact substring searches.Library Usage
None of the provided benchmark code uses any external libraries.
Special JavaScript Feature or Syntax
The benchmark does not use any special JavaScript features or syntax beyond what's standard in ECMAScript 5 (ES5). However, modern browsers have implemented various optimizations and improvements over ES5, such as includes
.
Other Alternatives
If you want to explore other string searching methods, here are a few alternatives:
string.indexOf()
with a regular expression: [string.indexOf('tempor', 0)]
. This can be slower than the native indexOf
method.String.prototype.includes()
with a custom substring: (string + '').includes('tempor')
. While this works, it's less efficient and may introduce unnecessary overhead due to string concatenation.Keep in mind that these alternatives are not typically recommended for performance-critical code or benchmarking purposes.