gpt4 book ai didi

c# - Find() 与 FirstOrDefault() 的性能对比

转载 作者:IT王子 更新时间:2023-10-29 03:36:39 26 4
gpt4 key购买 nike

<分区>

Similar Question:
Find() vs. Where().FirstOrDefault()

在具有单个字符串属性的简单引用类型的大序列中搜索 Diana 时得到了一个有趣的结果。

using System;
using System.Collections.Generic;
using System.Linq;

public class Customer{
public string Name {get;set;}
}

Stopwatch watch = new Stopwatch();
const string diana = "Diana";

while (Console.ReadKey().Key != ConsoleKey.Escape)
{
//Armour with 1000k++ customers. Wow, should be a product with a great success! :)
var customers = (from i in Enumerable.Range(0, 1000000)
select new Customer
{
Name = Guid.NewGuid().ToString()
}).ToList();

customers.Insert(999000, new Customer { Name = diana }); // Putting Diana at the end :)

//1. System.Linq.Enumerable.DefaultOrFirst()
watch.Restart();
customers.FirstOrDefault(c => c.Name == diana);
watch.Stop();
Console.WriteLine("Diana was found in {0} ms with System.Linq.Enumerable.FirstOrDefault().", watch.ElapsedMilliseconds);

//2. System.Collections.Generic.List<T>.Find()
watch.Restart();
customers.Find(c => c.Name == diana);
watch.Stop();
Console.WriteLine("Diana was found in {0} ms with System.Collections.Generic.List<T>.Find().", watch.ElapsedMilliseconds);
}

enter image description here

这是因为 List.Find() 中没有 Enumerator 开销,还是因为这加上其他原因?

Find() 运行速度几乎是原来的两倍,希望 .Net 团队将来不会将其标记为过时。

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