缓存 DataContractSerializer 实例是个好主意吗?
我正在编写一个 Windows 服务应用程序,该应用程序需要在执行期间重复序列化和反序列化 XML 文档。 由于我需要序列化和反序列化在编译期间未知的泛型类型(我事先不知道需要序列化/反序列化多少类型),我想知道保留缓存是否是个好主意我实例化的 DataContractSerializer 对象用于序列化和反序列化对象。
我问这个问题是因为我知道缓存 XmlSerializer 类实例是个好主意,因为它们在内存中创建动态程序集,并且在内存中动态创建的程序集不会被垃圾收集。
我读到 DataContractSerializer 依赖于轻量级代码生成,但我不熟悉它的细节。 这就是我问这个问题的原因,我需要了解如果我根据需要实例化 DataContractSerializer 实例,它会像 XmlSerializer 那样导致内存泄漏吗?
我选择使用 DataContractSerializer 而不是 XmlSerializer 来序列化内部属性。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
XmlSerializer
,它实际上取决于您是否使用简单的 构造函数(new XmlSerializer(typeToHandle)
),或更复杂的构造函数,允许您在运行时指定所有属性等。 如果您只使用简单的构造函数,它会重新使用后台程序集,因此不会有重复惩罚。我期望(但尚未测试)
DataContractSerializer
能够类似地工作; 但简单地缓存它当然没有什么坏处,也许在静态只读字段中请注意,
DataContractSerializer
限制了您可用的 xml 布局...只要您同意即可;- pWith
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 fieldNote that
DataContractSerializer
restricts the xml layout you have available to you... as long as you're OK with that ;-p