簡體   English   中英

轉換以下字節數組的最快方法是什么 - >類對象的集合

[英]What is the fastest way to convert the following byte array -> collection of class objects

我有一個字節數組,可以包含數百萬字節,並由以下結構表示:數組分為n個16字節的段。 每個段的前8個字節表示long類型的值(8個字節),后跟2個類型short(2 * 4個字節)的值。

我尋找將字節數組段轉換為以下類型的類對象集合的絕對最快方法:

public class Foo
{
    public long Value1 { get; set; }
    public float Value2 { get; set; }
    public float Value3 { get; set; }

    public Foo(long value1, float value2, float value3)
    {
        Value1 = value1;
        Value2 = value2;
        Value3 = value3;
    }
}

到目前為止我嘗試過的是使用BitConverter.ToInt64(...),...但是轉換需要太長時間,因為我必須處理數百萬字節和數百個這樣的數組的大小數組。

var collection = new List<Foo>();
        var byteArraySize = byteArray.Count();
        for (var counter = 0; counter < byteArraySize; counter += PacketLength) //Packetlength here is 16
        {
            collection.Add(new Foo(
                               BitConverter.ToInt64(byteArray, counter),
                               BitConverter.ToSingle(byteArray, counter + 8),
                               BitConverter.ToSingle(byteArray, counter + 12)));
        }

有人可以告訴我如何應用位移邏輯來加速這個過程。 使用指針邏輯的不安全代碼也可以工作。

非常感謝。

以下代碼需要4.668秒來處理我機器上的1 GiB數據,其中0.028秒用於轉換數據,4.641秒用於創建Foo對象。 您的原始代碼需要6.227秒。

unsafe Foo[] Load(byte[] buffer, int offset, int length)
{
    fixed (byte* ptr = buffer)
    {
        Data* data = (Data*)(ptr + offset);
        Foo[] result = new Foo[length / sizeof(Data)];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = new Foo(data);
            data++;
        }
        return result;
    }
}

struct Data
{
    public long Value1;
    public float Value2;
    public float Value3;
}

class Foo
{
    public long Value1 { get; set; }
    public float Value2 { get; set; }
    public float Value3 { get; set; }

    public unsafe Foo(Data* data)
    {
        Value1 = data->Value1;
        Value2 = data->Value2;
        Value3 = data->Value3;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM