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