gpt4 book ai didi

c# - 为什么在此示例中 LINQ 更快

转载 作者:可可西里 更新时间:2023-11-01 07:45:38 24 4
gpt4 key购买 nike

我编写了以下代码来测试使用 foreachLINQ 的性能:

private class Widget
{
public string Name { get; set; }
}

static void Main(string[] args)
{
List<Widget> widgets = new List<Widget>();
int found = 0;

for (int i = 0; i <= 500000 - 1; i++)
widgets.Add(new Widget() { Name = Guid.NewGuid().ToString() });

DateTime starttime = DateTime.Now;

foreach (Widget w in widgets)
{
if (w.Name.StartsWith("4"))
found += 1;
}

Console.WriteLine(found + " - " + DateTime.Now.Subtract(starttime).Milliseconds + " ms");

starttime = DateTime.Now;
found = widgets.Where(a => a.Name.StartsWith("4")).Count();

Console.WriteLine(found + " - " + DateTime.Now.Subtract(starttime).Milliseconds + " ms");

Console.ReadLine();
}

我得到如下输出:

31160 - 116ms31160 - 95 ms

在每次运行中,LINQ 的性能都比 foreach 高出约 20%。据我了解,LINQ 扩展方法在幕后使用标准 c#。

那么为什么 LINQ 在这种情况下更快?

编辑:

所以我更改了我的代码以使用秒表而不是日期时间,但仍然得到相同的结果。如果我先运行 LINQ 查询,那么我的结果显示 LINQ 比 foreach 慢大约 20%。这一定是某种 JIT 预热问题。我的问题是如何补偿测试用例中的 JIT 预热?

最佳答案

那是因为你没有热身。如果你颠倒你的情况,你会得到相反的结果:

31272 - 110ms
31272 - 80 ms

开始添加热身并使用秒表来更好地计时。

运行预热测试:

        //WARM UP:
widgets.Where(a => a.Name.StartsWith("4")).Count();

foreach (Widget w in widgets)
{
if (w.Name.StartsWith("4"))
found += 1;
}

//RUN Test
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();

found = widgets.Where(a => a.Name.StartsWith("4")).Count();
stopwatch1.Stop();

Console.WriteLine(found + " - " + stopwatch1.Elapsed);

found = 0;
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();

foreach (Widget w in widgets)
{
if (w.Name.StartsWith("4"))
found += 1;
}
stopwatch2.Stop();

Console.WriteLine(found + " - " + stopwatch2.Elapsed);

结果:

31039 - 00:00:00.0783508
31039 - 00:00:00.0766299

关于c# - 为什么在此示例中 LINQ 更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17147928/

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