views:

32

answers:

1

I have designed a class which is basically nothing but an object which stores a large number of properties of a piece of data. I have implemented IComparable in the class. Objects of the class are instantiated and stored in a List.

There is an added level of complexity in that certain fields of the object determine on which fields I sort (there is a hierarchy) The hierarchy is thus:

  • 1) Name (defined at instantiation)
  • 2) Product (defined at instantiation)
  • 3) NetGroup (defined post-instantiation, after initial creation of the list, I iterate back through, perform a calculation, and set the group.)
  • 4) Date (defined at instantiation)

There are several flags (bool fields) which determine if two of the above are used in the sort hierarchy.

  • 5) AllowProductGroupingInd (defined at instantiation)
  • 6) AllowDateGroupingInd (defined at instantiation)

The performance of the sort on a relatively small list (n = 1000) is poor, generally about 500 ms.

I'm unsure if I've implemented my comparer properly. My method looks like this:

    public int CompareTo(Exposure rfpe)
            {
                if (Name.CompareTo(rfpe.Name) != 0)
                    return Name.CompareTo(rfpe.Name);
                else
                {
                    if (AllowProductGroupingInd == false)
                    {
                        if (ProductId.CompareTo(rfpe.ProductId) != 0)
                            return ProductId.CompareTo(rfpe.ProductId);
                    }

                    if (NetGroup.CompareTo(rfpe.NetGroup) != 0)
                        return NetGroup.CompareTo(rfpe.NetGroup );
                    else if (AllowDateGroupingInd == false)
                    {
                        if (Date.CompareTo(rfpe.Date) != 0)
                            return Date.CompareTo(rfpe.Date);
                        else
                            return 0;
                    }

                    return 0;
                }

            }

I am using C# 3.0 so I cannot use LINQ. Is this a reasonable implementation of what I want to accomplish? Is there a more elegant solution? It seems to me I may be using too many conditionals, but I'm unsure how to get around that.

A: 

You appear to be double calling each of the subsidiary CompareTo methods, the first one being most likely the main culprit performance-wise.

int nameCompare = Name.CompareTo(rfpe.Name);

if (nameCompare != 0)
   return nameCompare;
else
   ...
Hightechrider