破坏 LINQ to 对象中的链接 Select() 是否会损害性能?
采用以下伪 C# 代码:
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
public IEnumerable<IDataRecord> GetRecords(string sql)
{
// DB logic goes here
}
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
var ids = GetRecords(sql).Select(record => (record["EmployerID"] as int?) ?? 0);
return ids.Select(employerID => new Employer(employerID) as IEmployer);
}
如果组合两个 Select() 调用,会更快吗?上面的代码中是否有额外的迭代?下面的代码是不是更快一些?
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
return GetRecords(sql).Select(record => new Employer((record["EmployerID"] as int?) ?? 0) as IEmployer);
}
我认为如果性能没有差异,第一个示例更具可读性。
Take the following pseudo C# code:
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
public IEnumerable<IDataRecord> GetRecords(string sql)
{
// DB logic goes here
}
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
var ids = GetRecords(sql).Select(record => (record["EmployerID"] as int?) ?? 0);
return ids.Select(employerID => new Employer(employerID) as IEmployer);
}
Would it be faster if the two Select() calls were combined? Is there an extra iteration in the code above? Is the following code faster?
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
return GetRecords(sql).Select(record => new Employer((record["EmployerID"] as int?) ?? 0) as IEmployer);
}
I think the first example is more readable if there is no difference in performance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有什么区别。
LINQ 使用延迟求值的思想,来源。我将引用相关部分:
基本上,直到您在
foreach
或.ToList()
等中使用Employers()
的结果,它实际上并没有完成任何工作。There is no difference.
LINQ uses the idea of delayed evaluation, source. I'll quote the relevant part:
Basically, until you use the result of
Employers()
in aforeach
or.ToList()
etc, it hasn't actually done any work.没有显着差异。这两种方法都返回一个可以循环 GetRecords 结果的表达式。
它们并不相同,因为第一个具有链接的选择,但它们仍然会以相同的顺序执行相同的工作。循环链接的 Select 时,第二个 Select 将根据需要将第一个 Select 中的项目一个又一个放入,第一个 Select 不必在第二个 Select 可以使用结果之前完成。
There is no significant difference. Both methods returns an expression that can loop through the result from GetRecords.
They are not identical, as the first one has chained Selects, but they will still do the same work and in the same order. When looping the chained Selects, the second select will put items one and one from the first Select as needed, the first Select doesn't have to complete before the second Select can use the result.