<div id='test'></div>
var arr = ['hello', 'a', 'b'];
let val;
for (var value of arr) {
if (value === 'b') {
val = value;
}
}
var arr = ['hello', 'a', 'b'];
let val = arr.find(node => node.id === 'b');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for..of | |
Array.find() |
Test name | Executions per second |
---|---|
for..of | 146496000.0 Ops/sec |
Array.find() | 160948016.0 Ops/sec |
The benchmark provided tests the performance of two different approaches to iterating through an array in JavaScript: the for...of
loop and the Array.find()
method. These two methods differ in execution style and their intended use cases.
for...of Loop
var arr = ['hello', 'a', 'b'];
let val;
for (var value of arr) {
if (value === 'b') {
val = value;
}
}
for..of
for...of
loop is designed to iterate over iterable objects, such as arrays. In this case, it checks each element in the array to see if it equals 'b'. If a match is found, it assigns that value to the variable val
.for...of
syntax is clear and easy to understand.Array.find() Method
var arr = ['hello', 'a', 'b'];
let val = arr.find(node => node === 'b');
Array.find()
Array.find()
method returns the first element in the array that satisfies the provided testing function. In this case, it searches for the first element that equals 'b'.for...of
since it stops searching after finding the first match, making it potentially faster in cases where a match occurs before the end of the array.for...of
since it only operates on arrays.The benchmark results show the performance of each method in terms of executions per second:
Array.find()
: 160,948,016.0 executions per secondfor..of
: 146,496,000.0 executions per secondFrom these results, it is evident that Array.find()
outperforms the for...of
loop in this specific case. This could be attributed to its short-circuiting behavior, which reduces unnecessary iterations once the desired element is found.
Several other alternatives can be considered when iterating or searching through arrays:
Traditional For Loop:
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 'b') {
// do something
}
}
Array.filter():
let found = arr.filter(node => node === 'b');
Array.some():
let exists = arr.some(node => node === 'b');
In summary, this benchmark illustrates the comparative performance of the for...of
loop and the Array.find()
method. While both approaches are suitable for looping through arrays, Array.find()
demonstrates superior performance in scenarios where a match is identified early in the search process. Depending on the use case, developers may choose between these options or explore traditional loops and other array methods based on performance and readability considerations.