C# Find vs FirstOrDefault

原文: C# Find vs FirstOrDefault

This article tells you when to get the first element of the array, which method to use higher performance.

We need to know that two methods are methods of Linq, Linq need to reference before use. For List, etc. are inherited enumerable Enumerablethen get the first element can be used FirstOrDefault. If you use the Findtype you need the array is IList.

The following write a simple example

Find decompile the code can be seen below, the following code to delete some code, so that we are more likely to see is for use Find and use judgment

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);
}

The FirstOrDefault code exists foreach, which calls the GetEnumerator method of the list, but also at the end of the call to Dispose. Such performance would FirstOrDefault slightly worse than 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);
}

So for the Listtype of first obtaining a default or use the Find, other useFirstOrDefault

  • For List, use for at twice the rate of foreach

  • Traversing the array is traversed twice the speed of List

  • Use for traversing the array using foreach to traverse speed is 5 times List

See also: https://stackoverflow.com/a/365658/6116637

Really want to compare the performance of for and foreach do? (Included performance comparison of the measured data) - walterlv


This article will be updated frequently, please read the original: https://blog.lindexi.com/post/C-Find-vs-FirstOrDefault.html , in order to avoid misleading the old error of knowledge, and a better reading experience.

If you want to continue to read my latest blog, please click on the RSS feed , it is recommended to use RSS Stalker subscribe to blog, or visit my homepage CSDN concern

Creative Commons License This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing. Welcome to reprint, use, repost, but be sure to keep the article signed by Linde Xi (containing links: https://blog.lindexi.com ), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification. If you have any questions, please contact me .

The following are advertising time

Recommended public concern Edi.Wang No.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12082241.html