const fruits = [
"Apple", "Banana", "Cherry", "Date", "Elderberry",
"Fig", "Grape", "Honeydew", "Iced Raspberry", "Jackfruit",
"Kiwifruit", "Lemon", "Mango", "Nectarine", "Orange",
"Peach", "Pear", "Quince", "Raspberry", "Strawberry",
"Tangerine", "Ugli Fruit", "Vine Fruit", "Watermelon", "Xigua"
];
var ARRAY = fruits.map((fruit) => ({name: fruit, desc: `Description ${fruit}`}));
let el;
for(var i=0; i < ARRAY.length; i++) {
if(ARRAY[i].name == 'Jackfruit') {
el = ARRAY[i];
break;
}
}
const el = ARRAY.find((obj) => obj.name === 'Jackfruit');
const el = ARRAY[ARRAY.findIndex((obj) => obj.name === 'Jackfruit')];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
Array.find | |
Array.findIndex |
Test name | Executions per second |
---|---|
For | 1197296.6 Ops/sec |
Array.find | 18027214.0 Ops/sec |
Array.findIndex | 10713032.0 Ops/sec |
I'll break down the provided JSON for you.
Benchmark Definition
The benchmark measures the performance of three different methods to search for an element in an array:
for
loop is used to iterate over the array and find the desired element.find()
method is used with a callback function to search for the first matching element in the array.findIndex()
method is used with a callback function to find the index of the first matching element in the array, and then access that element using indexing.Script Preparation Code
The script preparation code creates an array of objects (ARRAY
) by mapping each fruit name to an object with two properties: name
(the fruit name) and desc
(a description string).
Html Preparation Code
There is no HTML preparation code provided, which suggests that the benchmark is focused on JavaScript performance rather than DOM manipulation.
Library Used
None, as there are no external libraries used in the script preparation code.
Special JS Features or Syntax
The benchmark uses the following special JavaScript features:
desc
property of each object in the ARRAY
is created using template literals (the ${}
syntax).find()
and findIndex()
uses arrow functions (() => { ... }
).Options Compared
The benchmark compares the performance of three different methods:
for
loop is used to iterate over the array.find()
method is used with a callback function to search for the first matching element in the array.findIndex()
method is used with a callback function to find the index of the first matching element in the array, and then access that element using indexing.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
for
loop for large arrays.Other Considerations
When writing benchmarks, it's essential to consider factors like:
In this case, the benchmark only measures performance for a fixed-size array, so these considerations are less relevant.
As an alternative to this benchmark, you could also explore other methods, such as:
Array.prototype.some()
or Array.prototype every()