Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to cache DataContractSerializer instances?

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.

like image 854
CARLOS LOTH Avatar asked Jul 18 '09 11:07

CARLOS LOTH


People also ask

Does WCF Use Xml?

Windows Communication Foundation (WCF) can use two different serialization technologies to turn the data in your application into XML that is transmitted between clients and services, a process called serialization.

Which namespace is used for serialization in WCF?

DataContractSerializer as the Default By default WCF uses the DataContractSerializer class to serialize data types.

Is XmlSerializer safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application. The only thing left for you to do, is to devise a way to always retrieve the same instance.


1 Answers

...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

like image 97
Marc Gravell Avatar answered Oct 09 '22 13:10

Marc Gravell