gpt4 book ai didi

c# - LINQ Lambda 与查询语法性能

转载 作者:可可西里 更新时间:2023-11-01 08:06:09 29 4
gpt4 key购买 nike

我今天在我的项目中看到了一个 LINQ 查询语法,它正在计算 List 中具有特定条件的项目,如下所示:

int temp = (from A in pTasks 
where A.StatusID == (int)BusinessRule.TaskStatus.Pending
select A).ToList().Count();

我想通过使用 Count(Func) 重写它来重构它以使其更具可读性。我认为这在性能方面也会很好,所以我写道:

int UnassignedCount = pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);

但是当我使用 StopWatch 检查时,lambda 表达式耗时总是比查询语法多:

Stopwatch s = new Stopwatch();
s.Start();
int UnassignedCount = pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);
s.Stop();
Stopwatch s2 = new Stopwatch();
s2.Start();
int temp = (from A in pTasks
where A.StatusID == (int)BusinessRule.TaskStatus.Pending
select A).ToList().Count();
s2.Stop();

谁能解释一下为什么会这样?

最佳答案

我模拟了你的情况。是的,这些查询的执行时间是不同的。但是,这种差异的原因不是查询的语法。使用方法或查询语法并不重要。两者都会产生相同的结果,因为在编译之前,查询表达式会被翻译成它们的 lambda 表达式

但是,如果您注意到这两个查询根本不相同。您的第二个查询将在编译之前转换为它的 lambda 语法(您可以删除 ToList() 来自查询,因为它是多余的):

pTasks.Where(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending).Count();

现在我们有两个 lambda 语法的 Linq 查询。我上面提到的那个和这个:

pTasks.Count(x => x.StatusID == (int)BusinessRule.TaskStatus.Pending);

现在,问题是:
为什么这两个查询的执行时间不同?

让我们找出答案:
我们可以通过回顾这些来理解这种差异的原因:
- .Where(this IEnumerable<TSource> source, Func<TSource, bool> predicate).Count(this IEnumerable<TSource> source)

- Count(this IEnumerable<TSource> source, Func<TSource, bool> predicate) ;

这里是 Count(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 的实现:

public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
int count = 0;
foreach (TSource element in source) {
checked {
if (predicate(element)) count++;
}
}
return count;
}

这里是 Where(this IEnumerable<TSource> source, Func<TSource, bool> predicate) :

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
if (source is Iterator<TSource>)
return ((Iterator<TSource>)source).Where(predicate);
if (source is TSource[])
return new WhereArrayIterator<TSource>((TSource[])source, predicate);
if (source is List<TSource>)
return new WhereListIterator<TSource>((List<TSource>)source, predicate);
return new WhereEnumerableIterator<TSource>(source, predicate);
}

关注Where()执行。它将返回 WhereListIterator()如果你的收藏是 List,但是 Count()只会遍历源。在我看来,他们在 implementation 中做了一些加速WhereListIterator .之后我们调用Count()该方法不采用谓词作为输入,只会迭代过滤后的集合。


关于 WhereListIterator 的执行速度:

我找到了 this SO 中的问题: LINQ performance Count vs Where and Count 。你可以阅读@Matthew Watson answer那里。他解释了这两个查询之间的性能差异。结果是:Where迭代器避免了间接调用虚表,而是直接调用迭代器方法。正如您在该答案中看到的 call将发出指令而不是 callvirt .而且,callvirtcall 慢:

来自书CLR via C# :

When the callvirt IL instruction is used to call a virtual instance method, the CLR discovers the actual type of the object being used to make the call and then calls the method polymorphically. In order to determine the type, the variable being used to make the call must not be null. In other words, when compiling this call, the JIT compiler generates code that verifes that the variable’s value is not null. If it is null, the callvirt instruction causes the CLR to throw a NullReferenceException. This additional check means that the callvirt IL instruction executes slightly more slowly than the call instruction.

关于c# - LINQ Lambda 与查询语法性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576999/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com