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 | 15515875.0 Ops/sec |
Includes | 7510022.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare two approaches for searching a string: string.indexOf()
and string.includes()
. The goal is to measure which approach is faster in this specific use case.
Script Preparation Code
The script preparation code defines a variable string
containing a long text string. This string will be used as the input for both searches.
Html Preparation Code
There is no HTML preparation code provided, so it's likely that the benchmark is focused solely on JavaScript performance.
Individual Test Cases
There are two test cases:
string.indexOf('tempor') > -1
. This will return a boolean value indicating whether the substring 'tempor' is found in the original string.string.includes('tempor')
. This method returns a boolean value indicating whether the substring 'tempor' is found anywhere in the original string.Comparison
The two approaches being compared are:
string.indexOf()
: This method finds the index of the first occurrence of the specified substring. If the substring is not found, it returns -1.string.includes()
: This method checks if a specified value is present within the string. It returns true if the value is found, and false otherwise.Pros and Cons
Here are some pros and cons of each approach:
string.indexOf()
:string.includes()
:In this specific benchmark, string.indexOf()
is likely expected to be faster because it only needs to find the first occurrence of 'tempor', whereas string.includes()
needs to check every character in the string.
Library/ Framework Considerations
There isn't a specific library or framework mentioned in the benchmark definition. However, if we were to extend this benchmark to include other libraries or frameworks, we might need to consider factors like:
Special JS Features/Syntax
There doesn't appear to be any special JavaScript features or syntax being tested in this benchmark. The code only uses standard JavaScript constructs like variables, strings, and conditional statements.
Alternatives
If you wanted to modify this benchmark to explore different approaches, here are some alternatives:
string.indexOf()
with a custom implementation using loops or regular expressions.string.includes()
on smaller vs. larger input strings.By experimenting with these alternatives, you can gain a deeper understanding of JavaScript performance optimization techniques and how to apply them in your own code.