I'm doing some conversions between some structures and thier byte[]
representation. I found two way to do this but the difference (performance, memory and ...) is not clear to me.
Method 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;
}
Method 2:
public static T Deserialize<T>(byte[] buffer)
{
BinaryFormatter formatter = new BinaryFormatter();
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer))
{
return (T)formatter.Deserialize(stream);
}
}
so which one is better and what is the major difference?