多次调用ToList是否会影响性能? [英] Does calling ToList multiple times effect performance?

查看:154
本文介绍了多次调用ToList是否会影响性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到调用ToList将使查询每次都被执行.我对此有些困惑.因此,在这种情况下,第二次调用ToList是否会使查询多次执行?在什么情况下查询会多次执行?

I often times see that calling ToList will make query get executed every time. I'm a little confused about that. So in this scenario, would calling ToList the second time make the query get executed more than once? In what scenarios does the query get execute more than once?

//This gets from database and ToList is already called here
List<Customer> Customers = GetCustomersFromDataBase();

//ToList is called here again
List<Customer> FilteredCustomers = (from c in Customerswhere c.id == 1c).ToList();

编辑

我只是提供了此代码示例,以了解ToList的实际功能.我不是以这种方式实现它. 另外,我进行了一个存储过程调用,以从db返回客户并根据返回的数据表创建客户列表.

I just provided this code example to understand what ToList really does. I'm not implementing it this way. Also, I make a stored procedure call to return customers from db and create a list of customers from the returned datatable.

推荐答案

IQueryable上调用ToList(或ToArrayAsEnumerable等)将执行查询.之后,您使用的任何LINQ表达式都将在内存列表中进行操作.

Calling ToList (or ToArray, AsEnumerable, etc) on an IQueryable will execute the query. After that any LINQ expression you use will be operating on the in-memory list.

例如,您的代码:

List<Customer> Customers = GetCustomersFromDataBase();

这将导致表示数据库记录的Customer个对象的List个.现在,该列表与用于从数据库中获取结果的查询无关,尽管Customer对象中的链接记录仍需要从数据库中获取.

This will result in a List of Customer objects which represent the database records. The list is now independent of the query used to fetch the results from the database, although linked records in the Customer objects will still need to be fetched from the database.

然后,当您执行此操作时:

Then when you do this:

List<Customer> FilteredCustomers = (from c in Customers where c.id == 1c).ToList();

这不是对数据库进行操作,而是对上一条语句返回的内存结果进行操作.在这种情况下,您将不会多次查询数据库.

This is not operating on the database but on the results in memory that were returned from the previous statement. In this case you will not be querying the database multiple times.

影响的地方是当您拥有一个IQueryable对象并直接多次调用ToList时.在IQueryable上每次对ToList的调用都将导致对数据库的调用,所有伴随对象都将在后台进行跟踪.通常,这是您要避免的事情,尽管如果查询选择的记录总数很大并且过滤器提取数据的小子集,那么在枚举结果之前对查询进行附加过滤可能会带来更好的性能.

Where it does impact performance is when you have an IQueryable object that you call ToList on directly multiple times. Each call to ToList on an IQueryable will result in a call to the database, with all of the attendant object tracking and such in the background. Generally this is something you want to avoid, although additional filtering of the query prior to enumerating the results may result in better performance if the total number of records selected by the query is large and the filters pull small subsets of the data.

这篇关于多次调用ToList是否会影响性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆