I am wondering if there are performance implications of multiple .Where() statements. For example I could write:
var contracts = Context.Contract
.Where(
c1 =>
c1.EmployeeId == employeeId
)
.Where(
c1 =>
!Context.Contract.Any(
c2 =>
c2.EmployeeId == employeeId
&& c1.StoreId == c2.StoreId
&& SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
)
)
.Where(
c1 =>
!Context.EmployeeTask.Any(
t =>
t.ContractId == c1.Id
)
);
Or alternatively I could combine them all into the one Where() clause, like so:
var contracts = Context.Contract
.Where(
c1 =>
c1.EmployeeId == employeeId
&& !Context.Contract.Any(
c2 =>
c2.EmployeeId == employeeId
&& c1.StoreId == c2.StoreId
&& SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
)
&& !Context.Employee_Task.Any(
t =>
t.ContractId == c1.Id
)
);
Does the chain of Where() clauses hurt performance or are they equivalent?
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.
Yes, it's slower.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
In LINQ to Objects, there will be a very small performance hit, because basically the iterator chain will be longer - fetching the next element means going up a long chain of MoveNext() calls.
In LINQ to SQL and similar providers, I'd expect the same SQL to be generated either way, so it wouldn't impact performance there.
EDIT: Since writing this I've found out a bit more about the LINQ to Objects implementation - it's a little more complicated...
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