Question

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?

Was it helpful?

Solution 2

When using the BinaryFormatter to Serialize your data, it will append meta data in the output stream for use during Deserialization. So for the two examples you have, youll find it wont produce the same T output given the same byte[] input. So youll need to decide if you care about the meta data in the binary output or not. If you dont care, method 2 is obviously cleaner. If you need it to be straight binary, then you'll have to use something like method 1.

OTHER TIPS

You are talking about two different approaches and two different types of data. If you are working with raw values converted to Byte Array, go for the first method. If you are dealing with values serialized into Byte Array (they also contains serialization data), go for the second method. Two different situations, two different methods... they are not, let me say, "synonyms".

Int32 Serialized into Byte[] -> Length 54
Int32 Converted to Byte[]    -> Length 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top