哪种编组方法更好?

时间:2013-01-22 18:43:00

标签: c# bytearray structure marshalling

我找到了两种将byte[]转换为结构的方法。但我不知道这两种方法之间是否有任何区别?谁能知道哪个更好(性能,...)?

#1:

public static T ByteArrayToStructure<T>(byte[] buffer)
{
    int length = buffer.Length;
    IntPtr i = Marshal.AllocHGlobal(length);
    Marshal.Copy(buffer, 0, i, length);
    T result = (T)Marshal.PtrToStructure(i, typeof(T));
    Marshal.FreeHGlobal(i);
    return result;
}

#2:

public static T ByteArrayToStructure<T>(byte[] buffer)
{
    GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}

1 个答案:

答案 0 :(得分:2)

我使用以下代码为您做了基准测试:

const int ILITERATIONS = 10000000;

const long testValue = 8616519696198198198;
byte[] testBytes = BitConverter.GetBytes(testValue);

// warumup JIT
ByteArrayToStructure1<long>(testBytes);
ByteArrayToStructure2<long>(testBytes);

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();

for (int i = 0; i < ILITERATIONS; i++)
{
    ByteArrayToStructure1<long>(testBytes);
}

stopwatch.Stop();
Console.WriteLine("1: " + stopwatch.ElapsedMilliseconds);

stopwatch.Reset();

stopwatch.Start();

for (int i = 0; i < ILITERATIONS; i++)
{
    ByteArrayToStructure2<long>(testBytes);
}

stopwatch.Stop();
Console.WriteLine("2: " + stopwatch.ElapsedMilliseconds);

stopwatch.Reset();

stopwatch.Start();

for (int i = 0; i < ILITERATIONS; i++)
{
    BitConverter.ToInt64(testBytes, 0);
}

stopwatch.Stop();
Console.WriteLine("3: " + stopwatch.ElapsedMilliseconds);

Console.ReadLine();

我得出以下结果:

1: 2927
2: 2803
3: 51