如果从未调用终结器的性能损失
我有一堂带有终结器的课程。但由于我总是调用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要您正确实现这一点,并在对象上调用
GC.SuppressFinalize
,只有当用户不调用Dispose()
时,“惩罚”才会发生。话虽如此,“严厉”的处罚实际上在大多数情况下并没有那么严厉。如果您有许多带有终结器的短期对象会污染垃圾收集过程,这将是一个问题,但这很少是问题,因为带有终结器的对象很少(总体而言)。
As long as you implement this correctly, and call
GC.SuppressFinalize
on your object, the "penalty" will only occur when the user does not callDispose()
.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).
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/