Reputation: 487
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!
Upvotes: 1
Views: 3753
Reputation: 38094
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]);
}
Upvotes: 3