I was wondering if anyone knows if Array.find will short circuit the loop when the first item is found. I couldn't find anything googling.
Has anyone done any performance parisons between find and forEach?
I was wondering if anyone knows if Array.find will short circuit the loop when the first item is found. I couldn't find anything googling.
Has anyone done any performance parisons between find and forEach?
Share Improve this question asked Oct 16, 2019 at 15:52 techguy2000techguy2000 5,1716 gold badges36 silver badges53 bronze badges 7- I think it almost certainly does escape the loop – ControlAltDel Commented Oct 16, 2019 at 15:53
-
The docs for
find
explicitly state it returns as soon as the first match is found. – Dave Newton Commented Oct 16, 2019 at 15:53 - 3 Yes, it does, as the MDN page clearly states – Pointy Commented Oct 16, 2019 at 15:53
- 2 I'm voting to close this question as off-topic because this is not a benchmarking, not programming question – ControlAltDel Commented Oct 16, 2019 at 15:54
- ah. not sure how i missed it. it does say immediately return. so it think it's safe to assume it will be more performant than forEach – techguy2000 Commented Oct 16, 2019 at 15:56
3 Answers
Reset to default 9The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Array.find
will return the first result that matches the callback condition.
Performance wise they're both O(n), albeit find
is likely to cycle through less loops, therefore would be more performent in that respect.
I was wondering if anyone knows if Array.find will short circuit the loop when the first item is found.
Yes, it will. This is clear from the spec, which shows it bailing as soon as the callback has returned a truthy value. Step 6(d):
If
testResult
is true, returnkValue
.
(Separately, it would be odd to keep searching even though a result had been found. If there had been early spec language doing that, it would have been caught and corrected before being finalized, and/or challenged by the makers of JavaScript engines [and others] as being inefficient.)
As you can see the polyfill code in here, you can notice that find
loops until if there is something matched item.
Here is the part of that;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
So, ∀ n ∈ [0, len - 1]: n <= len - 1