I have this small code that takes an object and convert it to a byte[].
Using C# 4.0.
Can I optimize this further regarding speed then memory usage?
Even small changes would be great – calling this several thousand times+ per second.
public static byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
using (ms)
{
bf.Serialize(ms, obj);
}
return ms.ToArray();
}
The problem is that BinaryFormatter is using reflection to read the fields of your objects. Assume you have a simple class with 1 field:
If you serialize an array of those using BinaryFormatter, it will do something like that for each instance of Test:
The calls to GetField() will consume quite a lot of time.
You can significantly improve the speed using 3 ways:
Serialize everything manually. Something similar to this code:
Generate a custom serialization class on-the-fly using Reflection.Emit functionality. This is more generic and “clean”, but requires a lot of effort.
If you’re fine with it, use some third-party serializer that suits your needs.