简体   繁体   中英

C# sort array of structs

I am running a simulation part of which requires sort of array of pairs of values. When I used Array.Sort(v1,v2) it sorts 2 arrays based on first and all the simulation takes roughly 9 ms. But I need to sort based on first then second so I created array of structs. See my code below.

private struct ValueWithWeight : IComparable<ValueWithWeight>
{
    public double Value;
    public double Weight;
    public int CompareTo(ValueWithWeight other)
    {
        int cmp = this.Value.CompareTo(other.Value);
        if (cmp != 0)
            return cmp;
        else
            return this.Weight.CompareTo(other.Weight);
    }
} 

void Usage() 
{
    ValueWithWeight[] data = FillData();
    Array.Sort(data);
}

Now it takes roughly 27ms. Is there any better way to sort ?

Since you're going to extremely optimize it please consider following:

  1. Array.Sort runs over your array and performs comparison. In your case, there will not be unboxing since you implemented an interface on structure.

  2. Array.Sort performs swap of elements while sorting. Swapping is internally memmove. Your structure takes at least 16 bytes. You can try to reduce impact by allocating your double values in class. Class will always occupy IntPtr.Size bytes (because you will store pointers) so it should copy less bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM