var str = "penpineappleapplepen"
str.indexOf('pen') !== 1
str.startsWith('pen')
str.endsWith('pen')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
startsWith | |
endsWith |
Test name | Executions per second |
---|---|
indexOf | 23249282.0 Ops/sec |
startsWith | 32660182.0 Ops/sec |
endsWith | 33301332.0 Ops/sec |
I'll explain the benchmark and its options in detail.
Benchmark Overview
The provided benchmark measures the performance of three string methods: indexOf
, startsWith
, and endsWith
. These methods are used to search for a substring within a larger string. The benchmark uses a fixed string "penpineappleapplepen"
as input, which contains both the target substring ("pen") and its reverse.
Methods Compared
The benchmark compares the performance of three different approaches:
indexOf
method: This method returns the index of the first occurrence of the specified substring within the string.startsWith
method: This method returns a boolean indicating whether the string starts with the specified substring.endsWith
method: This method returns a boolean indicating whether the string ends with the specified substring.Pros and Cons
indexOf
method:startsWith
and endsWith
methods:indexOf
, as they only check the first or last characters of the string, respectively. They are also faster than indexOf
for small substrings.Library and Purpose
The benchmark uses the JavaScript String.prototype.indexOf
, String.prototype.startsWith
, and String.prototype.endsWith
methods, which are part of the ECMAScript standard. These methods provide a convenient way to search for substrings within strings.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax used in this benchmark. However, it does utilize some internal optimizations provided by the JavaScript engine, such as:
str
variable is defined using template literals, which allows for more readable and efficient string concatenation.Alternatives
Other alternatives for searching substrings within strings include:
str.contains
, which provides more advanced substring search functionality.Keep in mind that these alternatives may not be as efficient as the built-in methods used by modern JavaScript engines.