Quantcast
Viewing latest article 7
Browse Latest Browse All 10

XmlSerializer and XmlRootAttribute Performance Issue

I have been working with xml serialization over the last week or so and ran into a strange issue today. It only came to light when I decided to implement IXmlSerializable and write my own methods for reading and writing the xml. I posted recently about using he XmlRootAttribute as a fix for the xmlns='' > was not expected error I was seeing. This all worked fine and dandy until I really started to utilize that method over and over again in my code. I found the performance of this to be horrible...so horrible in fact it was taking 2-3 minutes to deserialize a moderately complex 1MB xml file. After doing some digging (on "The Google") I discovered that microsoft decided to only implement caching on the Xml serializer when you use one of the two "more common" constructors (see documentation). Of course it would seem the one I need would not be one of them.

I was thinking of somehow adding the XmlSerializers for each type/root pair that I was using to the application level cache or something like that but thought that might bring with it its own set of challenges. I found a great article here on stack overflow that shows a possible workaround for the problem using a static class to act as a cache or you.

Please note this code is taken directly from the article above:


public static class XmlSerializerCache
{
private static readonly Dictionary cache =
new Dictionary();

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];
}
}

Here is how you use it to create an XmlSerializer object:


var xmlRootAttribute = new XmlRootAttribute("ExampleElement");
var serializer = XmlSerializerCache.Create(target.GetType(), xmlRootAttribute);

After implementing that I was still experiencing the 2-3 minute deserialization one the first call but all subsequent calls to that code with similar xml took only 2 seconds.

NOTE:
Seems microsoft is in the habit of only half implementing caching in their code. This problem is almost identical to the problems with the CrossListQueryCache object in SharePoint....where they again only implemented caching for two of the four available method signatures. Here is an interesting article I found in the nether-regions of cyberspace where microsoft state this half implementation is by design...

Technorati Tags: , , , , , , ,


Viewing latest article 7
Browse Latest Browse All 10

Trending Articles