0

我找到了两种转换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;
}
4

1 回答 1

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
于 2013-01-22T19:04:57.970 回答