# Monday, 13 June 2005

Sigh.  It’s a constant battle.  I knew full well that XmlSerializer leaks temp assemblies if you don’t use the right constructor.  (The one that takes only a type will cache internally, so it’s not a problem.)  And then I went and wrote some code that called one of the other constructors without caching the resulting XmlSerializer instances. 

The result:  one process I looked at had over 1,500 instances of System.Reflection.Assembly on the heap.  Not so good. 

The fix?  Not as simple as I would have hoped.  The constructor that I’m using takes the Type to serialize, and an XmlRootAttribute instance.  It would be nice to be able to cache the serializers based on that XmlRootAttribute, since that’d be simple and all.  Unfortunately, two instances of an XmlRootAttribute with the same parameters return different values to GetHashCode(), so it’s not that easy.  I ended up using a string key compounded from the type’s full name and the parameters I’m using on XmlRootAttribute.  Not the most beautiful, but it’ll work.  Better than having 1,500 temp assemblies hanging around.

Work | XML
Friday, 22 July 2005 13:49:13 (Pacific Daylight Time, UTC-07:00)
I share with you a workaround I found when serializing an ArrayList (when all the items are the same Type, that is "MyClass")

You'll see 3 examples:
1- Serializing the ArrayList "as is" (memory leak)
2- Caching the XmlSerlializer instance (works fine)
3- Converting the ArrayList to a typed array (best solution)


Hope you find this useful.

Comments are closed.