Given:
Dim values = {"First", "Second", "Third", "Fourth", "Fifth"}
Dim searchValue = "fourth"
Dim isPresent = False
Is it more efficient to do this:
isPresent = values.Any(Function(x) String.Compare(x, searchValue, True) = 0)
or this:
For Each value In values
If (String.Compare(value, searchValue, True) = 0) Then
isPresent = True
Exit For
End If
Next
Basically, my question is: does the Any
method short-circuit -- as the For Each
loop does -- when it encounters its first element that satisfies the predicate, and if that is the case, does it do so any faster than the O(n) of the For Each
operation shown above?
Please note: my question is not about finding a string in a collection of strings. I know there are plenty of ways to accomplish that. My question is more general than that -- about the efficiency of the LINQ Any
method vs. the For Each
loop approach.
Also, I have reviewed What is the Efficiency and Performance of LINQ and Lambda Expression in .Net? and Find an item in List by LINQ?, among other resources, and they don't answer my question, and I wasn't able to find anything that does.