Search code examples
vb.netlistsortingmaxmin

math.min and math.max vs sort for efficiently finding values in a list


In visual basic when trying to find the largest and smallest values in a list is it more efficient to use math.min/max like so:

Dim highest As Decimal = Decimal.MinValue
Dim lowest As Decimal = Decimal.MaxValue

For Each item As Decimal In listNumber
    highest = Math.Max(highest, item)
    lowest = Math.Min(lowest, item)
Next

or to sort the list and grab the values by index like so:

listNumber.Sort()
listNumber(0)
listNumber(99)

It looks like using min/max is the preferred method, but they both seem to work well enough for a list of 100 decimal values, is one more efficient than the other or is this just a 6 vs half dozen sort of thing?

I tried to find a way to benchmark this in Visual Studio 2013 Express, but it looks like I would have to upgrade to Visual Studio Ultimate, did I miss something?


Solution

  • Sorting the items means that you won't only find out which one is the largest and smallest, you will also arrange all items in between according to value. Although it's simple to do, it's still extra work that you don't have to make the computer do.

    You can use the Min and Max methods to get what you want just as easily as sorting the list:

    Dim highest As Decimal = listNumber.Min()
    Dim lowest As Decimal = listNumber.Max()