假设:
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?以及其他资源,他们没有回答我的问题,而且我找不到任何相关内容。
答案 0 :(得分:1)
答案 1 :(得分:1)
Enumerable.Any
是implemented 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
代码。