析构函数会影响性能吗?

Do destructors affect performance?

我已经在我的一个基础 类 中添加了一个析构函数,我用它来帮助寻找内存泄漏,如下所示:

#if DEBUG
~BaseViewModel()
{
    Debug.WriteLine("View Model Disposed");
}
#endif

甚至删除 Debug.WriteLine 代码

存在析构函数会影响调试构建的性能吗?

According to Microsoft Documentation

Empty finalizers should not be used. When a class contains a finalizer, an entry is created in the Finalize queue. When the finalizer is called, the garbage collector is invoked to process the queue. An empty finalizer just causes a needless loss of performance.

仅当 class 中有非托管资源时,才需要析构函数(终结器)。如果你添加一个析构函数,你应该在 Dispose 中抑制 Finalization。否则会导致你的对象在内存中驻留的时间更长,因为它们会被添加到终结器队列中。 (注:Read how Finalization works)。