<div id='test'></div>
var arr = [];
for (let i = 0; i < 100; i++) {
arr.push(i);
}
let val;
for(i=0; i<arr.length; i++){
var value = arr[i];
if (value === 98) {
val = value;
break;
}
}
let val;
for (var value of arr) {
if (value === 98) {
val = value;
break;
}
}
let val = arr.find(node => node.id === 98);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-loop | |
for..of | |
Array.find() |
Test name | Executions per second |
---|---|
for-loop | 227461.6 Ops/sec |
for..of | 709191.5 Ops/sec |
Array.find() | 4273374.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Overview
The benchmark compares three different approaches to find an element in an array:
i
.Options being compared
The benchmark is testing which approach is faster and more efficient in terms of executions per second.
Pros and Cons of each approach:
Library usage
None of the benchmark tests use any external libraries. However, the Array.find()
method is a built-in method on the Array prototype, which means it's implemented by the browser itself and doesn't rely on any external libraries.
Special JavaScript features or syntax
The only special feature used in this benchmark is the for...of
loop, which was introduced in ECMAScript 2015 (ES6). This loop uses a more modern syntax to iterate over arrays and can be faster and more efficient than traditional for loops.
Other alternatives
If you wanted to compare other approaches to find an element in an array, some examples include:
forEach()
method with a callback functionfilter()
method followed by indexOf()
However, these approaches may not be as efficient or elegant as the native for-loop or Array.find()
methods used in this benchmark.