简体   繁体   English

C#结构排序数组

[英]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. 当我使用Array.Sort(v1,v2)时,它首先根据2个数组进行排序,所有模拟过程大约需要9毫秒。 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. 现在大约需要27毫秒。 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. Array.Sort在您的数组上运行并执行比较。 In your case, there will not be unboxing since you implemented an interface on structure. 在您的情况下,由于您在结构上实现了接口,因此不会取消装箱。

  2. Array.Sort performs swap of elements while sorting. Array.Sort在排序时执行元素交换。 Swapping is internally memmove. 交换是内部记忆。 Your structure takes at least 16 bytes. 您的结构至少需要16个字节。 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. 类将始终占用IntPtr.Size字节(因为您将存储指针),因此它应复制较少的字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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