var array = [];
for (let i = 0 ; i < 10000 ; i++) {
array.push ({ value: Math.floor (Math.random () * 1000) });
}
const value = Math.floor (Math.random () * 1000);
let found = undefined;
for (let i = array.length - 1 ; i >= 0 ; i--) {
const cell = array[i];
if (cell.value === value) {
found = cell;
break;
}
}
const value = Math.floor (Math.random () * 1000);
let found = array.find ((cell) => cell.value === value);
const value = Math.floor (Math.random () * 1000);
let found = array.find (function (cell) { return cell.value === value });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reversed for loop | |
find method => | |
find method function |
Test name | Executions per second |
---|---|
reversed for loop | 469430.2 Ops/sec |
find method => | 860505.5 Ops/sec |
find method function | 855161.8 Ops/sec |
The benchmark titled "find reversed for loop versus find method 2" compares three different approaches to find an object in an array of objects, where each object has a property value
. The key operations tested are:
Reversed For Loop:
value
.Array find
Method (Arrow Function):
find
method with an arrow function. This method searches the array and returns the first element that satisfies the provided testing function (where cell.value
matches value
).this
keyword when using an arrow function.Array find
Method (Regular Function):
find
method but with a traditional function expression instead of an arrow function.this
context differently depending on how the function is called, which might or might not be an issue depending on the context.According to the benchmark results:
find method =>
(with arrow function) demonstrated the highest performance at approximately 860,505 executions per second.find method function
(regular function) performs nearly as well, at approximately 855,161 executions per second.reversed for loop
came in at the lowest with approximately 469,430 executions per second.The choice between these methods often depends on the context of code usage:
find
with an appropriate function) is often more important than micro-optimizations.In summary, the benchmark highlights the balance between code readability and performance in JavaScript when searching arrays, showcasing the trade-offs for developers to consider when writing and optimizing code.