Home > front end >  C# LINQ: is calling .Where() multiple times bad for performance?
C# LINQ: is calling .Where() multiple times bad for performance?

Time:08-28

If I want to query a database is it better to make 1 call to .Where() with a large set of conditions or can I make several successive calls to .Where with smaller conditions?

e.g.

_db.Person.Where(p => p.Name = X && p.Age > 1 && p.Face == Attractive)

or

var person = _db.Person.Where(p => p.Name = X)
person = person.Where(p => p.Age > 1)
person = person.Where(p => p.Face == Attractive)

To filter results I presume LINQ has to loop over items. Does LINQ .Where have any optimisation features to prevent the second approach impacting performance?

CodePudding user response:

Linq-to-SQL and Entity Framework do not work like that. They translate the query into a single SQL query, therefore it's not going to make the slightest bit of difference which one you do, as either way you get the same SQL, which the database engine will compile using the best indexes available.

In fact, even if the conditions are flipped it will not make a difference on the vast majority of DBMSs, because of the way they compile the SQL, using indexes and statistics to reorder conditions and so on.


Linq-To-Objects on the other hand will be very slightly faster. It still won't need to loop the whole list again if you have multiple Where. What it actually does is something like this

var person = list.Where(p => yourCondition && previousConditions)

But because each one is in a separate lambda there is a slight overhead to an extra function call.

Furthermore, the logic would be reversed: the last condition is checked first.

  • Related