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') >= 0
string.includes('tempor')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes |
Test name | Executions per second |
---|---|
IndexOf | 12553744.0 Ops/sec |
Includes | 10058702.0 Ops/sec |
Let's break down the provided JSON and explain what's being tested in this JavaScript microbenchmark.
Benchmark Definition
The benchmark is defined by two test cases:
IndexOf
: Tests if the indexOf()
method returns a non-negative index for a specific substring within a given string.Includes
: Tests if the includes()
method returns true
when a specific substring exists within a given string.Script Preparation Code
The script preparation code is a JavaScript variable assignment that creates a sample string:
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.';
This code is executed once before running the benchmark.
Test Case Options
There are two test case options:
indexOf()
returns a non-negative index for the substring 'tempor'
.includes()
returns true
when searching for the substring 'tempor'
.Pros and Cons of Each Approach
IndexOf:
Pros:
includes()
since it only needs to find the first occurrence of the substring.Cons:
-1
if the substring is not found.Includes:
Pros:
indexOf()
since it returns a boolean value indicating whether any part of the string matches the search string.Cons:
indexOf()
due to the additional overhead of searching for all occurrences.true
if at least one character in the string matches the search string.Library and Purpose
In this benchmark, the includes()
method uses the JavaScript built-in String.prototype.includes()
method. This method returns a boolean value indicating whether any part of the string matches the search string.
Special JS Feature or Syntax
There are no special features or syntax used in this benchmark that would require specific knowledge to understand.
Other Alternatives
For this type of benchmark, alternative approaches could include:
string.match()
with a regular expression to search for the substring.Note that these alternatives are not currently being tested in this benchmark.