var sampleOptions = ['прицеп полуприцеп', 'прицеп картофелевоз'];
var options = Array.from(Array(1000)).map((_, i) => sampleOptions[i % 2]);
options.filter(option => option.startsWith('прицеп'));
options.filter(option => option.includes('картофел'));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
startsWith | |
includes |
Test name | Executions per second |
---|---|
startsWith | 63180.5 Ops/sec |
includes | 38920.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The provided benchmark is comparing two approaches to filter an array of strings: startsWith
and includes
. The filtering criteria are based on the presence of certain substrings in the strings.
Script Preparation Code
The script preparation code generates an array of 1000 strings, with each string containing either "прицеп" or "картофелевоз". This is done using JavaScript's Array.from()
method and a closure to map over the array and create new strings.
Html Preparation Code
There is no HTML preparation code provided, so we'll assume that the benchmark is running in a headless browser environment (e.g., Chrome Headless).
Library Usage
The filter()
method is used in both test cases. The filter()
method is a built-in JavaScript array method that takes a callback function as an argument. The callback function tests each element of the array against the specified condition, and returns a boolean value indicating whether the element passes the test. If the returned values are truthy, the elements are included in the new array; if they're falsy, they're excluded.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax being used in this benchmark.
Pros and Cons of Approaches
Now, let's compare the two approaches:
startsWith()
method, which returns a boolean value indicating whether the string starts with the specified substring.includes()
for more general filtering scenarios.includes()
method, which returns a boolean value indicating whether the string includes the specified substring.startsWith()
for certain edge cases.Other Considerations
The choice between startsWith
and includes()
ultimately depends on the specific use case and performance requirements. If you need to filter an array of strings based on exact matches, startsWith()
might be a better choice. However, if you're dealing with more general filtering scenarios or want to avoid potential performance differences, includes()
might be a better option.
Other Alternatives
If you need to filter arrays in JavaScript, there are other alternatives to the filter()
method:
However, in this specific benchmark, filter()
is being used to achieve a concise and readable way to filter arrays based on simple conditions.