gpt4 book ai didi

c# - 哪个更快 : Single(predicate) or Where(predicate). Single()

转载 作者:IT王子 更新时间:2023-10-29 04:06:15 28 4
gpt4 key购买 nike

讨论来自 this answer让我好奇。哪个更快:

someEnumerable.Single(predicate);

someEnumerable.Where(predicate).Single();

毕竟,第一个更短、更简洁,而且似乎是专门设计的。

甚至 ReSharper 也建议前者:

enter image description here

我在上一篇文章中争论过,它们在功能上是相同的,并且应该具有非常相似的运行时间。

最佳答案

LINQ 到对象

没有什么比基准更能回答这样的问题了:

(已更新)

class Program
{
const int N = 10000;
volatile private static int s_val;

static void DoTest(IEnumerable<int> data, int[] selectors) {
Stopwatch s;

// Using .Single(predicate)
s = Stopwatch.StartNew();
foreach (var t in selectors) {
s_val = data.Single(x => x == t);
}
s.Stop();
Console.WriteLine(" {0} calls to Single(predicate) took {1} ms.",
selectors.Length, s.ElapsedMilliseconds);

// Using .Where(predicate).Single()
s = Stopwatch.StartNew();
foreach (int t in selectors) {
s_val = data.Where(x => x == t).Single();
}
s.Stop();
Console.WriteLine(" {0} calls to Where(predicate).Single() took {1} ms.",
selectors.Length, s.ElapsedMilliseconds);
}


public static void Main(string[] args) {
var R = new Random();
var selectors = Enumerable.Range(0, N).Select(_ => R.Next(0, N)).ToArray();

Console.WriteLine("Using IEnumerable<int> (Enumerable.Range())");
DoTest(Enumerable.Range(0, 10 * N), selectors);

Console.WriteLine("Using int[]");
DoTest(Enumerable.Range(0, 10*N).ToArray(), selectors);

Console.WriteLine("Using List<int>");
DoTest(Enumerable.Range(0, 10 * N).ToList(), selectors);

Console.ReadKey();
}
}

有些令人震惊的是,.Where(predicate).Single() 以大约两倍的优势获胜。我什至将这两个案例都运行了两次,以确保缓存等不是一个因素。

1) 10000 calls to Single(predicate) took 7938 ms.
1) 10000 calls to Where(predicate).Single() took 3795 ms.
2) 10000 calls to Single(predicate) took 8132 ms.
2) 10000 calls to Where(predicate).Single() took 4318 ms.

更新结果:

Using IEnumerable<int>  (Enumerable.Range())
10000 calls to Single(predicate) took 7838 ms.
10000 calls to Where(predicate).Single() took 8104 ms.
Using int[]
10000 calls to Single(predicate) took 8859 ms.
10000 calls to Where(predicate).Single() took 2970 ms.
Using List<int>
10000 calls to Single(predicate) took 9523 ms.
10000 calls to Where(predicate).Single() took 3781 ms.

关于c# - 哪个更快 : Single(predicate) or Where(predicate). Single(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21194750/

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