Is it useful to cache instances of DataContractSerializer?

I am writing a Windows application that needs to serialize and deserialize XML documents multiple times during its execution. Since I need to serialize and deserialize common types that are not known at compile time (I don't know a priori how many types I need for serialization / deserialization). I would like to know if it is good to store the cache of DataContractSerializer objects. I am creating an instance to serialize and deserialize objects.

I ask this question because I know that it is recommended to cache instances of the XmlSerializer class, because they create a dynamic assembly in memory under the hood, and assemblies dynamically created in memory do not collect garbage.

I read that the DataContractSerializer is based on generating lightweight code, but I'm not used to its details. That's why I ask this question, I need to understand, if I create DataContractSerializer instances as necessary, will this lead to a memory leak, since there will be an XmlSerializer?

I decided to use a DataContractSerializer instead of an XmlSerializer to serialize internal properties.

+6
caching xml-serialization windows-services datacontractserializer
source share
1 answer

... it is recommended to cache instances of the XmlSerializer class, as they create a dynamic assembly in memory under the hood ...

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

I would expect (but not check) the DataContractSerializer to work the same way; but, of course, there is no harm in simple caching, possibly in a readonly static field

Note that the DataContractSerializer limits the xml layout available to you ... while you are fine with this; -p

+4
source share

All Articles