指定XmlRootAttribute当XmlSerializer的性能问题 [英] XmlSerializer Performance Issue when Specifying XmlRootAttribute
问题描述
目前,我有一个很奇怪的问题,我似乎无法弄清楚如何解决它。
I'm currently having a really weird issue and I can't seem to figure out how to resolve it.
我有一个的非常的复杂的类型,我尝试使用XmlSerializer类序列化。这其实是精功能和类型序列化正常,但似乎需要的非常的很长一段时间这样做;约5秒,这取决于该对象中的数据。
I've got a fairly complex type which I'm trying to serialize using the XmlSerializer class. This actually functions fine and the type serializes properly, but seems to take a very long time in doing so; around 5 seconds depending on the data in the object.
在进行位分析我已经缩小的问题下来 - 奇怪的是 - 到指定XmlRootAttribute调用XmlSerializer.Serialize时。我这样做是为了改变一个集合的名称被序列化从ArrayOf的东西多一点有意义的。有一次,我删除了参数的操作几乎瞬间!
After a bit of profiling I've narrowed the issue down - bizarrely - to specifying an XmlRootAttribute when calling XmlSerializer.Serialize. I do this to change the name of a collection being serialized from ArrayOf to something a bit more meaningful. Once I remove the parameter the operation is almost instant!
任何想法或建议将是极好的,我完全难倒这一个!
Any thoughts or suggestions would be excellent as I'm entirely stumped on this one!
推荐答案
只是为别人谁运行到这个问题;手持上面我设法使用下面的类来解决这个问题的答案,从MSDN的例子:
Just for anyone else who runs into this problem; armed with the answer above and the example from MSDN I managed to resolve this issue using the following class:
public static class XmlSerializerCache
{
private static readonly Dictionary<string, XmlSerializer> cache =
new Dictionary<string, XmlSerializer>();
public static XmlSerializer Create(Type type, XmlRootAttribute root)
{
var key = String.Format(
CultureInfo.InvariantCulture,
"{0}:{1}",
type,
root.ElementName);
if (!cache.ContainsKey(key))
{
cache.Add(key, new XmlSerializer(type, root));
}
return cache[key];
}
}
然后,而不是使用默认的XmlSerializer的构造函数需要一个XmlRootAttribute,我用下面的代替:
Then instead of using the default XmlSerializer constructor which takes an XmlRootAttribute, I use the following instead:
var xmlRootAttribute = new XmlRootAttribute("ExampleElement");
var serializer = XmlSerializerCache.Create(target.GetType(), xmlRootAttribute);
我的应用程序现在已经执行了!
My application is now performing again!
这篇关于指定XmlRootAttribute当XmlSerializer的性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!