Is there any performance difference between these two approaches?
// First approach, iterating until a match
public bool Find(IEnumerable<Object> allObjects, Object testObj)
{
foreach (Object obj in allObjects)
{
if (obj.Equals(testObj))
{ return true; }
}
return false;
}
// Second approach, using LINQ and Any()
public bool Find(IEnumerable<Object> allObjects, Object testObj)
{
var query = from Object obj in allObjects where obj.Equals(testObj) select obj;
return query.Any();
}
My question is whether the LINQ version compares testObj to all objects in the collection and then the Any() method checks if the resulting collection is empty. This would be generally less efficient than the first case where the iteration stops after the first match.
No, the performance should be equivalent –
Any()will stop iterating over the source enumeration after the first match.Also you could do this more concise (and easier to read and understand, but that’s a matter of opinion) using method syntax: