XmlSerializer.Deserialize() 对于超过 1MB 的文件太慢 - .Net Compact Framework 3.5 sp1
我得到了一个 XML 架构,我使用 xsd.exe 为其生成一个类 FooClass
。
我正在从主机接收 xml 请求,我从目录中获取它们,并使用 XmlSerializer.Deserialize()
获取我的 FooClass
的实例。
嗯,到目前为止,这一切都很完美,而且仍然如此,但突然我开始获取更大的 XML 文件(大约 300KB),并且 Deserialize()
所需的时间是不可接受的!使用 XMLTextReader()
加载相同的 XML 文件需要几毫秒,反序列化的时间约为 1 分 30 秒!
所以我想我会使用XMLReader来读取XML文件并自己构建FooClass
! 但在我开始重新编写所有代码之前,我想问您是否有一种方法可以使用 XmlSerializer.Deserialize()
更快?
我不确定 XMLSerializer Assembly 是否会对我有很大帮助?
这是我的代码,它将在每个文件的循环中调用
using (MemoryStream ms = new MemoryStream(xmldata)
{
XmlSerializer sz = new XmlSerializer(typeof(FooClass));
foo = (FooClass)sz.Deserialize(ms);
}
提前致谢, AK
I got a XML schema for which I used xsd.exe to generate a Class FooClass
.
I am receiving xml requests from host which I get them from a directory and use the XmlSerializer.Deserialize()
to get a Instance of my FooClass
.
Well, this worked till now perfectly and it still does, but suddenly I started to get XML files which are larger (about 300KB) and the time which it takes to Deserialize()
is not acceptable! Loading the same XML file with XMLTextReader()
takes milliseconds and the time to deserialize is about 1 minute and 30 seconds!
So I thought I'll use the XMLReader to read the XML file and build FooClass
by myself!
But before I start to rework all my code, I would like to ask you if there is a way to use XmlSerializer.Deserialize()
which would be faster?
I am not sure if XMLSerializer Assembly would help me much here?
here is my code which will be called in a Loop for each file
using (MemoryStream ms = new MemoryStream(xmldata)
{
XmlSerializer sz = new XmlSerializer(typeof(FooClass));
foo = (FooClass)sz.Deserialize(ms);
}
Thanks in advance,
AK
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过 .NET 3.5 中的新
DataContractSerializer
?使用它的方式与 XmlSerializer 几乎相同;我不知道它是否更快,但它比XmlSerializer
有许多其他好处,例如序列化私有成员、不需要无参数构造函数、能够忽略属性等。您需要添加
[DataContract]
属性添加到FooClass
的定义中,您不必这样做,但我通过用装饰它们来明确告诉序列化器我想要序列化哪些成员>[数据成员]
。Have you tried the new
DataContractSerializer
in .NET 3.5? The way you use it is pretty much the same asXmlSerializer
; whether it's any faster I don't know, but it has many other benefits over theXmlSerializer
such as serialising private members, not needing a parameterless constructor, being able to ignore properties etc.You will need to add the
[DataContract]
attribute toFooClass
's definition, and you don't have to, but I explicitly tell the serialiser which members I want serialising by decorating them with[DataMember]
.