Is it a good idea to cache DataContractSerializer instances?
Asked Answered
D

1

6

I'm writing a windows service application that needs to serialize and deserialize XML documents repeatedly during its execution. As I need to serialize and deserialize generic types that are not known during compilation time (I don't know a priori how many types I need to serialize/deserialize) I'd like to know if it is a good idea do keep a cache of DataContractSerializer objects I instantiate for serializing and deserializing the objects.

I'm asking this question because I know it is a good idea to cache the XmlSerializer class instances since they create a dynamic assembly in memory under the hood and the assemblies dynamically created in memory are not garbage collected.

I read that the DataContractSerializer relies on lightweight code generation, but I'm not usual with the details of it. That is why I'm asking this question, I need to understand if I instantiate DataContractSerializer instances as needed it would lead me to a memory leak as the XmlSerializer would?

I have chose to use the DataContractSerializer instead of the XmlSerializer for being able to serialize internal properties.

Dugger answered 18/7, 2009 at 11:27 Comment(0)
A
4

...it is a good idea to cache the XmlSerializer class instances since they create a dynamic assembly in memory under the hood...

With XmlSerializer, it actually depends on whether you use the simple constructor (new XmlSerializer(typeToHandle)), or the more complex constructors that allow you to specify all the attributes etc at runtime. If you only use the simple constructor it re-uses the background assembly, so there is no repeat penalty.

I would expect (but haven't tested) DataContractSerializer to work similarly; but there is certainly no harm in simply caching it, perhaps in a static readonly field

Note that DataContractSerializer restricts the xml layout you have available to you... as long as you're OK with that ;-p

Anterior answered 18/7, 2009 at 11:37 Comment(2)
Do you know which restrictions are impost to the xml layout when using the DataContractSerializer? I'd like to know just to make sure I'm ok with that :PDugger
There is no equivalent of [XmlAttribute], being the most obvious. If your main aim is to serialize data, it is fine (as are various others). If your main aim is to write xml in a specific layout, it can be troublesome.Anterior

© 2022 - 2024 — McMap. All rights reserved.