XmlSerializer Memory Leak

XML serialization is the process of converting an object’s public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer. For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

Some of the Overloaded XmlSerializer constructors internally calls XmlSerializer.GenerateTempAssembly to generate the temporary assembly every time the constructor is called. The bad part is it does not reuse the existing created assembly, rather it creates the new temporary assembly for every call, which in turn increases the memory foot print.

One of the solutions is to cache the reference and reuse the assembly using the below code:

public class XmlSerializerCache{
private static object SyncRoot = new object();
private static Dictionary Serializers = new Dictionary();
public static XmlSerializer GetSerializer(Type type, Type[] types)
{
StringBuilder keyBuilder = new StringBuilder(60);
keyBuilder.Append(type.FullName);
if (null != types && types.Length > 0)
{
foreach (Type t in types)
keyBuilder.Append(“#”).Append(t.FullName);
}
string key = keyBuilder.ToString();
XmlSerializer serializer = null;
if (false == Serializers.TryGetValue(key, out serializer))
{
lock (SyncRoot)
{
if (false == Serializers.TryGetValue(key, out serializer))
{
serializer = new XmlSerializer(type, types);
Serializers.Add(key, serializer);
}
}
}
return serializer as XmlSerializer;
}
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.