I'm trying to determine if there is a change in the Big O equivalence of a nested loop when I use a LINQ select instead.
public void myFunc(List<Foo> fooList, List<Bar> barList)
{
foreach(Foo foo in fooList)
{
foreach(Bar bar in barList)
{
if(foo.PropA == bar.PropA && bar.PropZ.HasValue)
foo.PropC = foo.PropB * bar.PropZ;
}
}
}
I believe this nested loop example is O(n^2) for complexity.
I replaced the nested loop with a LINQ select like this:
public void myFunc(List<Foo> fooList, List<Bar> barList)
{
foreach(Foo foo in fooList)
{
Bar bar = (from b in barList
where foo.PropA == b.PropA
select b).FirstOrDefault();
if(bar.PropZ.HasValue)
foo.PropC = foo.PropB * bar.PropZ;
}
}
If nothing else, the code appears to be a little cleaner to read as it explicitly states "we're looking for this particular Bar
to work with."
My question is this: Does using the LINQ select reduce the Big O complexity?
bar
s and filter onbar.PropZ.HasValue
first, if you expect more than a tiny amount to evaluate to false? Doesn't really answer your question, I am just reviewing your code.foo.PropA == bar.PropA
is true for multiple entries inbarList
? Edit: definitively not as the second one will throw aNullReferenceException
when the select returnsnull
..FirstOrDefault()
will make the linq loop exit early if a match is found, while your dumb nested loops do not exit early, so yes, I would think that linq will have a better big-oh. But I am not sure, hence a comment and not an answer.