本文告诉大家,在获得数组第一个元素时,使用哪个方法性能更高。
需要知道,两个方法都是 Linq 的方法,使用之前需要引用 Linq 。对于 List 等都是继承可枚举Enumerable
这时获取第一个元素可以使用FirstOrDefault
。如果使用Find
那么需要数组的类型是IList
。
下面写一个简单的例子
反编译 Find 可以看到下面代码,下面的代码删了一些代码,让大家比较容易看到 Find 使用的是 for 然后使用判断
private T[] _items;
public T Find(Predicate<T> match)
{
for (int index = 0; index < this._size; ++index)
{
if (match(this._items[index]))
return this._items[index];
}
return default (T);
}
而 FirstOrDefault 的代码存在 foreach ,这会调用列表的 GetEnumerator 方法,而且还会在结束的时候调用 Dispose 。这样 FirstOrDefault 的性能就比 Find 稍微差一些。
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
foreach (TSource source1 in source)
{
if (predicate(source1))
return source1;
}
return default (TSource);
}
所以在对于 List
类型的获得第一个或默认请使用 Find ,其他的请使用FirstOrDefault
参见:https://stackoverflow.com/a/365658/6116637
真的要比较 for 和 foreach 的性能吗?(内附性能比较的实测数据) - walterlv
本文会经常更新,请阅读原文: https://lindexi.gitee.io/lindexi/post/C-Find-vs-FirstOrDefault.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://lindexi.gitee.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有