Search code examples
c#performancelinq

Min() and Max() or single oldschool foreach?


If I have big collection and I care about performance, should I believe in miracle and use

var min = Y.Min();
var max = Y.Max();

or I better be a good engineer and use

var max = double.NegativeInfinity;
var min = double.PositiveInfinity;
foreach(var y in Y)
{
    if(y > max)
        max = y;
    if(y < min)
        min = y;
}

Y is ICollection<double>, because I need Count and foreach. I am curious if type is right, because of min/max and that I will need to iterate collection from end, so there will be

Y.OrderByDescending((o) => o)...

Solution

  • There's no "magic" to Linq that will optimize queries like that. All it does is add iterators on top of the collections. Linq is designed to improve coding efficiency, not raw performance.

    There may be cases where a Linq query will perform faster than a foreach, but this isn't one of them. Min and Max are two separate operations, so the compiler would have to "look ahead" to see what operations are being done to know whether they could be combined into a single iteration. It's not that sophisticated.