I have the following scenario: I want to process an array of boolean values by checking if all values match true.
For that, I've used array.allSatisfy({ $0 == true }) but I was thinking about using !array.contains(false) because they return the same result but I don't know if there's any difference in performance (readibility is out of question because it's evident that allSatisfy is more readable).
One famous LLM said that contains is better than allSatisfy because it stops in the first mismatch detected but I have strong doubts about this, because both are O(n) according to documentation and it's expected that allSatisfy does the same mechanism.
So the question is: Are they have the same performance or is there any notable difference? I think that they perfom the same way or, if not, the difference in performance is neglible.
Intuitively, contains would be more performant as it does not need to invoke a function for each element. That could also lead to better compiler optimizations.
Both allSatisfy and contains will stop their search as soon as a counterexample/example is found.
I might add that contains also reads better to me, but that’s just personal preference.
If Sequence is composed of Equatable elements and capable of direct access to element, contains(_ element:) will use _customContainsEquatableElement to retrieve the result. Array, as I see, does not have implemented this method, so will behave like contains(where: {}).
In short: all of them have the same performance in Array and only will get improvement using contains(_ element:) if using another type of Sequence with Equatable elements.