简体   繁体   中英

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

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?

eg

_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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM