缓存 DataContractSerializer 实例是个好主意吗?

发布于 2024-07-27 03:45:39 字数 469 浏览 2 评论 0原文

我正在编写一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青瓷清茶倾城歌 2024-08-03 03:45:39

...缓存 XmlSerializer 类实例是个好主意,因为它们在内存中创建动态程序集...

使用 XmlSerializer,它实际上取决于您是否使用简单的 构造函数(new XmlSerializer(typeToHandle)),或更复杂的构造函数,允许您在运行时指定所有属性等。 如果您只使用简单的构造函数,它会重新使用后台程序集,因此不会有重复惩罚。

期望(但尚未测试)DataContractSerializer 能够类似地工作; 但简单地缓存它当然没有什么坏处,也许在静态只读字段中

请注意,DataContractSerializer 限制了您可用的 xml 布局...只要您同意即可;- p

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文