Where(Func<TSource, bool> predicate).FirstOrDefault() vs. FirstOrDefault(Func<TSource, bool> predicate);

What do You expect from next part of code:

   1:  void Main()
   2:  {
   3:      var stopWatch = new Stopwatch();
   4:      const int max = 100000000;
   5:      List<int> list = new List<int>();
   6:   
   7:      //insert max amount of numbers into collection    
   8:      var rnd = new Random(max/10000);
   9:      int rn = 0;
  10:      for (int i = 1; i < max; i++)
  11:      {
  12:          rn = rnd.Next(i);
  13:          list.Add(rn);
  14:      }
  15:      
  16:      Console.WriteLine("Where(a => a == rn).FirstOrDefault()");    
  17:      stopWatch.Start();
  18:      int r1 = list.Where(a => a == rn).FirstOrDefault();
  19:      Console.WriteLine("{0} ticks - {1} ms", stopWatch.ElapsedTicks, stopWatch.ElapsedMilliseconds);
  20:      
  21:      Console.WriteLine();        
  22:      Console.WriteLine("FirstOrDefault(a => a == rn)");
  23:      stopWatch.Restart();    
  24:      int r2 = list.FirstOrDefault(a => a == rn);
  25:      Console.WriteLine("{0} ticks - {1} ms", stopWatch.ElapsedTicks, stopWatch.ElapsedMilliseconds);
  26:      
  27:      stopWatch.Stop();    
  28:  }

Output:

Where(a => a == rn).FirstOrDefault()
1964564 ticks - 836 ms

FirstOrDefault(a => a == rn)
3306927 ticks - 1407 ms

All because of different realization of queries:

- public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) – returns the firsts element in TSource
- public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) – has to realize iterator and compares to predicate result for every member.

However, public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) is much better optimized for looking for by predicate. Together with FirstOrDefault() You can receive result dramatically faster.          

My first post

Hi everyone!

I started my blog. And hope You will find something useful here.

Have fun!

Twitter