System.Linq.Enumerable.Any()的效率

时间:2014-12-03 15:46:22

标签: .net performance linq

假设:

Dim values = {"First", "Second", "Third", "Fourth", "Fifth"}
Dim searchValue = "fourth"
Dim isPresent = False

这样做效率更高:

isPresent = values.Any(Function(x) String.Compare(x, searchValue, True) = 0)

或者这个:

For Each value In values
    If (String.Compare(value, searchValue, True) = 0) Then
        isPresent = True
        Exit For
    End If
Next

基本上,我的问题是:当Any方法遇到满足谓词的第一个元素时,For Each方法是短路 - 就像For Each循环那样 - 如果是这样的话,它是否比上面显示的Any操作的O(n)更快?

请注意:我的问题不是在字符串集合中查找字符串。我知道有很多方法可以实现这一目标。我的问题比这更普遍 - 关于LINQ For Each方法与{{1}}循环方法的效率。

另外,我已经审核了What is the Efficiency and Performance of LINQ and Lambda Expression in .Net?Find an item in List by LINQ?以及其他资源,他们没有回答我的问题,而且我找不到任何相关内容。

3 个答案:

答案 0 :(得分:1)

他们完全一样。 Any()的实现会在找到单个匹配元素后立即短路。

来自documentation

  

一旦确定结果,就会停止源的枚举。

答案 1 :(得分:1)

Enumerable.Anyimplemented as

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) {
        if (predicate(element)) return true;
    }
    return false;
}

因此,当找到该项目时,它将会爆发。

除此之外,你应该使用String.Equals Method (String, String, StringComparison)重载来比较字符串是否相等而忽略大小写。 String.Compare对订购更有用。

答案 2 :(得分:1)

反编译Any方法以查看它的作用......

foreach (TSource source1 in source)
{
    if (predicate(source1))
        return true;
}
return false;

您可以看到这相当于您发布的For Each代码。