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') === true
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes |
Test name | Executions per second |
---|---|
IndexOf | 206624160.0 Ops/sec |
Includes | 214766064.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
What is being tested?
The benchmark measures the performance difference between two string methods:
string.indexOf('tempor') > -1
string.includes('tempor') === true
Both methods are used to search for a specific substring ("tempor") within a large string.
Options compared
The benchmark compares two approaches:
indexOf()
: This method returns the index of the first occurrence of the specified value, or -1 if it's not found. It returns an integer value.includes()
: This method returns true
if the string includes the specified value, and false
otherwise.Pros and Cons
indexOf()
:includes()
since it only needs to find a single character match (if any) and return an integer result.includes()
:indexOf()
since it needs to search for all occurrences, not just one.Library and its purpose
In this benchmark, the string
object is used, which is a built-in JavaScript object that provides various string methods. The includes()
method is part of the ECMAScript standard and was introduced in ECMAScript 2015 (ES6).
Special JS feature or syntax
None are mentioned here.
Other alternatives
If you wanted to compare other approaches for searching within strings, you might consider:
test()
method instead of indexOf()
or includes()
.string.includes()
(not applicable here since it's built-in).In summary, this benchmark measures the performance difference between two commonly used string methods in JavaScript: indexOf()
and includes()
. The results can help developers optimize their code for better performance, especially when working with large strings.