I am running a test.
It looks like:
method 1)
List<int> = new List<int>{1,2,4, .....} //assume 1000k
var result ErrorCodes.Where(x => ReturnedErrorCodes.Contains(x)).First();
method 2)
List<int> = new List<int>{1,2,4, .....} //assume 1000k
var result = ErrorCodes.Where(x => ReturnedErrorCodes.Contains(x)).ToArray()[0];
Why is method 2 is so slow compared to method 1?
Erm… because you are creating an extra array (rather than just using the iterator). The first approach stops after the first match (
Whereis a non-buffered streaming API). The second loads all the matches into an array (presumably with several re-sizes), then takes the first item.As a side note; you can create infinite sequences; the first approach would still work, the second would run forever (or explode).
It could also be:
(that won’t make it any faster, but is perhaps easier to read)