<div id='test'></div>
var arr = [
{text: "foo"},
{text: "bar"},
{text: "baz"},
];
let val;
for(var i=0; i<arr.length; i++){
var value = arr[i];
if (value.text === 'baz') {
val = value;
break;
}
}
let val;
for (var value of arr) {
if (value.text === 'baz') {
val = value;
break;
}
}
let val = arr.find(node => node.text === 'baz');
let val;
for(var i=arr.length-1; i>-1; i--){
var value = arr[i];
if (value.text === 'b') {
val = value;
break;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-loop | |
for..of | |
Array.find() | |
reverse for |
Test name | Executions per second |
---|---|
for-loop | 94802936.0 Ops/sec |
for..of | 32459766.0 Ops/sec |
Array.find() | 183797840.0 Ops/sec |
reverse for | 86085656.0 Ops/sec |
The provided benchmark tests evaluate the performance of different JavaScript methods for searching through an array of objects. Specifically, it compares the following approaches:
Traditional for-loop
let val;
for(var i=0; i<arr.length; i++){
var value = arr[i];
if (value.text === 'baz') {
val = value;
break;
}
}
for...of loop
let val;
for (var value of arr) {
if (value.text === 'baz') {
val = value;
break;
}
}
Array.find() method
let val = arr.find(node => node.text === 'baz');
undefined
if no value satisfies it.Reverse for-loop
let val;
for(var i=arr.length-1; i>-1; i--){
var value = arr[i];
if (value.text === 'baz') {
val = value;
break;
}
}
From the benchmark results, the performance metrics (Executions Per Second) indicate the following:
Array.find()
.Other alternatives could include:
forEach() method: This provides a functional approach similar to Array.find()
, but it's generally less performant as it does not handle early termination (i.e., a break
statement isn't possible).
Map and Filter methods: These can be used for transforming arrays and operating on elements but do not serve the search intent directly and may result in unnecessary overhead.
In practice, the choice of approach often depends on the specific use case, the performance requirements, and consideration of readability and maintainability of the code.