If you know, with some degree of certainty, that the element you seek is closer to the end (right side) of the array, using for() loop instead of find could be beneficial. You would construct your for() loop to start in reverse, hence it will travel only the length from the end to the element. E.g.looking for 99 in [1..100]. The for() will only compare 2 elements, whereas find will compare 99 elements.
Elaboration on Performance.
I found it odd that everything I read so far was stating that find() is faster than for() [in forward search], because when I ran it few times I observed the opposite, i.e. find() was about 30%-50% slower. Like this:
So I ran it 1 million times, then I averaged the performance time. To clarify the premise:
I created an array of 100,000 elements. Each elements is an object with 2 elements, with key = number from 0 to 100,000, and the array was sorted by the key. From this array I attempted to find the object with key=97900, which is towards the end.
let arr = [{key: 1, value: 1},...]
Results (average time in ms)
a) Find: 0.078452628 ms
b) For: 0.217990078 ms
c) For [reversed]: 0.000223515 ms
From the plot we can see that for() has more unpredictable outliers. We can also observe that at the beginning find() has slower performance.
If you want to run tests by yourself, here is some starter code:
let arr = [];
for (let i = 0; i < 100000; i++) {
arr.push({
key: i,
value: i ^ 2
});
}
console.log("find() vs for() vs reverse for() 97,900 in 100,000, array of objects")
console.time("find")
arr.find(i => {
return i.key === 97900
})
let find = console.timeEnd("find")
console.time("for")
for (let i = 0; i < arr.length; i++) {
if (arr[i].key === 97900) {
break
}
}
console.timeEnd("for")
console.time("for-rev")
for (let i = arr.lenght - 1; i > 0; i--) {
if (arr[i].key === 97900) {
break
}
}
console.timeEnd("for-rev")
find
returnsundefined
instead ofnull
, if not found.find()
, it is probably a highly-optimized loop in a lower-level language.