1

I've used BinaryFormatter in order to serialize/deserialize objects to a byte array. But it's too slow. Here's my code:

IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, this);
stream.Close();
byte[] currentByteArray = stream.ToArray();

Is it possible to improve that code, in order to speed it up. Or what is my alternatives? I've seen several other serializatiors like xmlserialization but I don't want to write it to file, just as a byte array.

Thanks in advance!

8
  • Please include the class code and the metrics in your question.
    – Oguz Ozgul
    Nov 19, 2015 at 8:18
  • also, how big is teh serialized data? what size are we talking about here?
    – lordkain
    Nov 19, 2015 at 8:19
  • 2
    stream.Close(); should be after byte[] currentByteArray = stream.ToArray();, not before Nov 19, 2015 at 8:31
  • Are you serializing dataobjects? like for communication? Nov 19, 2015 at 8:44
  • @DmitryBychenko No. It should be in a finally block after the .ToArray(). In fact, stream should just be in a using block.
    – Aron
    Nov 19, 2015 at 9:28

1 Answer 1

3

Your code can be improved if you place disposing in finally statement like guys said in comments:

IFormatter formatter;
MemoryStream stream;
try
{
    formatter = new BinaryFormatter();
    stream = new MemoryStream();
    formatter.Serialize(stream, this);
    byte[] currentByteArray = stream.ToArray();
}
finally
{
   if(stream!=null)
      stream.Close();
}

However, the above code does not improve performance of BinaryFormatter class cause it works and is used correctly. But you can use other libraries.

One of the fastest and general purpose serializer in .NET is Protobuf-net. For example:

[ProtoContract]
class SubMessageRepresentations
{
   [ProtoMember(5, DataFormat = DataFormat.Default)] 
   public SubObject lengthPrefixedObject;
   [ProtoMember(6, DataFormat = DataFormat.Group)]
   public SubObject groupObject;
}

[ProtoContract(ImplicitFields=ImplicitFields.AllFields)]
class SubObject { public int x; }


using (var stream = new MemoryStream()) {
  _pbModel.Serialize(
   stream, new SubMessageRepresentations {
        lengthPrefixedObject = new SubObject { x = 0x22 },
        groupObject = new SubObject { x = 0x44 }
   });
byte[] buf = stream.GetBuffer();
for (int i = 0; i < stream.Length; i++)
Console.Write("{0:X2} ", buf[i]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.