var text = 'jdkxshklhkhskhskshkjaFREDERICKBCDBKlkhdslkbsklbsjbjkd';
text.includes('FREDERICK');
text.indexOf('FREDERICK') !== -1;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
indexOf |
Test name | Executions per second |
---|---|
includes | 5640741.5 Ops/sec |
indexOf | 7570530.0 Ops/sec |
Let's break down the benchmark test and explain what's being tested, compared, and considered.
What is being tested?
The benchmark tests two different approaches to search for a string within a given text: includes
method vs indexOf
method.
What are the options being compared?
Two options are being compared:
includes
method checks if a specified string exists within another string. It returns true
if the string is found, and false
otherwise.indexOf
method searches for the first occurrence of a specified value in a string. It returns the index of the first match, or -1 if not found.Pros and Cons:
Both methods have their own pros and cons:
true
for partial matches (e.g., "hello world")includes
Library and Purpose:
The text
variable used in the benchmark is an example of a JavaScript string. The includes
and indexOf
methods are both part of the ECMAScript standard, which means they are widely supported across different browsers and environments.
Special JS Feature/Syntax:
There are no special JavaScript features or syntaxes mentioned in this benchmark.
Other Alternatives:
Other alternatives to these two methods include:
RegExp.test()
) for more complex string matching_.includes()
or _indexOf()
) for more functional programming-style string searchingBenchmark Preparation Code:
The script preparation code creates a sample string variable text
with a specific value, which is used in both benchmark test cases. This ensures that the same text is being searched across both tests.
Individual Test Cases:
Each test case measures the execution time of either the includes
or indexOf
method on the same text string. By comparing these two results, we can see which approach performs better in terms of speed.
In this benchmark, it appears that the includes
method is faster than the indexOf
method for searching a single occurrence of a string within a larger text. However, this may not always be the case, and other factors like device, browser, and system configuration can influence performance results.