I'm surprised that it apparently doesn't matter whether i prepend or append LINQ extension methods.
Tested with Enumerable.FirstOrDefault
:
hugeList.Where(x => x.Text.Contains("10000")).FirstOrDefault();
hugeList.FirstOrDefault(x => x.Text.Contains("10000"));
var hugeList = Enumerable.Range(1, 50000000) .Select(i => new { ID = i, Text = "Item" + i }); var sw1 = new System.Diagnostics.Stopwatch(); var sw2 = new System.Diagnostics.Stopwatch(); sw1.Start(); for(int i=0;i<1000;i++) hugeList.Where(x => x.Text.Contains("10000")).FirstOrDefault(); sw1.Stop(); sw2.Start(); for(int i=0;i<1000;i++) hugeList.FirstOrDefault(x => x.Text.Contains("10000")); sw2.Stop(); var result1 = String.Format("FirstOrDefault after: {0} FirstOrDefault before: {1}", sw1.Elapsed, sw2.Elapsed); //result1: FirstOrDefault after: 00:00:03.3169683 FirstOrDefault before: 00:00:03.0463219 sw2.Restart(); for (int i = 0; i < 1000; i++) hugeList.FirstOrDefault(x => x.Text.Contains("10000")); sw2.Stop(); sw1.Restart(); for (int i = 0; i < 1000; i++) hugeList.Where(x => x.Text.Contains("10000")).FirstOrDefault(); sw1.Stop(); var result2 = String.Format("FirstOrDefault before: {0} FirstOrDefault after: {1}", sw2.Elapsed, sw1.Elapsed); //result2: FirstOrDefault before: 00:00:03.6833079 FirstOrDefault after: 00:00:03.1675611 //average after:3.2422647 before: 3.3648149 (all seconds)
I would have guessed that it would be slower to prepend Where
since it must find all matching items and then take the first and a preceded FirstOrDefault
could yield the first found item.
Q: Can somebody explain why i'm on the wrong track?