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]);
}