我正在开发一个紧凑的框架应用程序,需要提高性能。该应用程序当前通过将对象序列化为 XML 并将它们存储在数据库中来离线工作。使用分析工具我可以看到这是相当大的开销,减慢了应用程序的速度。我想如果我切换到二进制序列化,性能会提高,但是因为紧凑框架不支持这一点,所以我查看了 protobuf-net。序列化似乎更快,但反序列化要慢得多,并且应用程序进行的反序列化比序列化更多。
二进制序列化应该更快吗?如果是,我能做些什么来加快性能?这是我如何使用 XML 和二进制文件的片段:
XML序列化:
public string Serialize(T obj)
{
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
serializer.Serialize(stream, obj);
stream = (MemoryStream)writer.BaseStream;
return encoding.GetString(stream.ToArray(), 0, Convert.ToInt32(stream.Length));
}
public T Deserialize(string xml)
{
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream(encoding.GetBytes(xml));
return (T)serializer.Deserialize(stream);
}
Protobuf-net 二进制序列化:
public byte[] Serialize(T obj)
{
byte[] raw;
using (MemoryStream memoryStream = new MemoryStream())
{
Serializer.Serialize(memoryStream, obj);
raw = memoryStream.ToArray();
}
return raw;
}
public T Deserialize(byte[] serializedType)
{
T obj;
using (MemoryStream memoryStream = new MemoryStream(serializedType))
{
obj = Serializer.Deserialize<T>(memoryStream);
}
return obj;
}