El TecnoBaúl de Kiquenet

Kiquenet boring stories

Posts Tagged ‘leaks’

XmlSerializer Performance issues and assembly leaks

Posted by kiquenet en 14 julio 2014

The problem is not new: it is well documented (section Dynamically Generated Assemblies) and there are numerous forum and blog posts about it; but still, I bumped on it again a few days ago. Some of .NET’s XmlSerializer constructors may lead to memory leaks and serious performance issues.

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(

        if (!cache.ContainsKey(key))
            cache.Add(key, new XmlSerializer(type, root));

        return cache[key];

the XmlSerializer class documentation discusses a workaround:

If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable,as shown in the following example.


Workaround for XmlSerializer assembly leaks

Posted in Performance | Etiquetado: , , | Leave a Comment »