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

If I have a large collection and care about performance, I have to believe in miracles and use

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

or better to 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 ICollection<double>because I need Countand foreach. I am curious if the type is right, due to min / max and that I will need to iterate the collection from the end, so that will be

Y.OrderByDescending((o) => o)...
+4
source share
3 answers

There is no β€œmagic” in Linq that will optimize such queries. All he does is add iterators over collections. Linq is designed to improve coding efficiency, not raw performance.

, Linq , foreach, . Min Max , " ", , , , . .

+4

, Y IEnumerable<double>, Y.Max(), , System.Linq.Enumerable.Max() ( , System.Core.dll):

public static double Max(this IEnumerable<double> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    double num = 0.0; // current max
    bool flag = false; // is first iteration
    foreach (double num2 in source)
    {
        if (flag)
        {
            if (num2 > num || double.IsNaN(num))
            {
                num = num2;
            }
        }
        else // initialization case
        {
            num = num2;
            flag = true;
        }
    }
    if (flag) // throw if there were no elements
    {
        return num;
    }
    throw Error.NoElements();
}

, - , , , - - , .

+1

SortedList :

var list = new SortedList<double, double> { { 4, 4}, { 9, 9}, { 7, 7} };
var min = list.Keys[0];
var max = list.Keys[list.Count - 1];

The first value will always be min, last max. Doesn't help much with order, as it rises. In addition, it is not very efficient to embed it, so if you care about the performance of its creation (as opposed to reading from it), this is not such an excellent choice.

+1
source

All Articles