如果从未调用终结器的性能损失

发布于 2024-10-15 15:09:22 字数 331 浏览 2 评论 0原文

我有一堂带有终结器的课程。但由于我总是调用 Dispose() 并且 Dispose() 正在调用 GC.SupressFinalize(this),我认为我的对象实际上从未使其进入终结队列。终结器只是作为后备,以防该类的另一个用户忘记调用 Dispose()。

即使从未调用过终结器并且对象从未进入终结队列,仅实现终结器是否会带来性能损失?

我曾经认为不会,但在 Bill Wagner 的Effective C#:第二版的第 102 页上,它说:“即使它从未被调用,终结器的存在确实会带来相当大的性能损失你的类型。”

I have a class with a finalizer. But since I'm always calling Dispose() and Dispose() is calling GC.SupressFinalize(this), I think my object never actually makes it into the finalization queue. The finalizer is just in there as a backstop in case another user of the class forgets to call Dispose().

Is there any performance penalty for just implementing a finalizer even if its never called and the object never makes it to the finalization queue?

I used to think not, but on page 102 of Effective C#: Second Edition by Bill Wagner, it says, "Even if it's never called, the presence of a finalizer does introduce a rather large performance penalty for your types."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

一杆小烟枪 2024-10-22 15:09:22

即使从未调用过终结器并且对象从未进入终结队列,仅实现终结器是否会带来性能损失?

只要您正确实现这一点,并在对象上调用 GC.SuppressFinalize,只有当用户不调用 Dispose() 时,“惩罚”才会发生。

话虽如此,“严厉”的处罚实际上在大多数情况下并没有那么严厉。如果您有许多带有终结器的短期对象会污染垃圾收集过程,这将是一个问题,但这很少是问题,因为带有终结器的对象很少(总体而言)。

Is there any performance penalty for just implementing a finalizer even if its never called and the object never makes it to the finalization queue?

As long as you implement this correctly, and call GC.SuppressFinalize on your object, the "penalty" will only occur when the user does not call Dispose().

That being said, the "severe" penalty is actually not all that severe in most cases. It would be a problem if you had many short lived objects with finalizers polluting your garbage collection process, but that's rarely a problem, since objects with finalizers are rare (overall).

陪你搞怪i 2024-10-22 15:09:22

IIRC,终结器的问题是带有它们的对象会存活一个额外的垃圾回收周期。然而,这只适用于调用终结器的情况。本文解释得很好: http:// anasoft.wordpress.com/2007/06/17/more-about-gc-dispose-and-finalize/

IIRC, the problem with finalizers is that objects with them survive for an extra gc cycle. This only applies if the finalizer is called, however. This article explains it well: http://anasoft.wordpress.com/2007/06/17/more-about-gc-dispose-and-finalize/

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