I know this may sound duplicate question (like this or this ) but I wanted some clarity regarding the number iterations that will take place in this query.
My assumptions are as follows:
lets say I have collection of 1000 items.
In Where() query, it iterates through each and every item and add it to IEnumerable. i.e. it will need O(n) always.
foreach (var item in myList)
{
if(//<condition>)
{
//add it to list/enumerable
}
//continue through entire list
}
In FirstOrDefault(<condition>)
query,it starts iterating through the collection and breaks the loop as soon as it gets the item matching the <condition>
and returns single element or only if no item is matching <condition>
then it will iterate through entire list.
so complexity can be from O(1) to O(n)
foreach (var item in myList)
{
if(//<condition>)
{
//return item
break;
}
}
if this is correct then it will always be better to use FirstORDefault for a single item return.?
Where
is actually deferred - i.e. it does not have any cost until the enumeration happens.
Where
looks kind of like this, and returns a new IEnumerable<T>
.
foreach (var item in enumerable)
{
if (condition)
{
yield return item;
}
}
FirstOrDefault
returns T
.
FirstOrDefault
will stop checking (i.e. break) when/if it finds anything.
edit:
However, as Daniel pointed out, Where
is deferred, so you can also stop iterating yourself and it will have the same performance as FirstOrDefault
(although then you might as well just use FirstOrDefault)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With