简体   繁体   English

哪种编组方法更好?

[英]which marshalling method is better?

I found two method to convert byte[] to structure. 我发现了两种将byte[]转换为结构的方法。 but I don't know if there is any difference between these two methods? 但是我不知道这两种方法之间是否有区别? can anyone know which is better (performance, ...)? 谁能知道哪个更好(性能,...)?

#1: #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: #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;
}

I did a benchmark for you using the following code: 我使用以下代码为您做了一个基准测试:

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();

I came to the following results: 我得出以下结果:

1: 2927
2: 2803
3: 51

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

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