Costs associated with C # destructors (aka: finalizers)?

The destructor must free the unmanaged resources that your object belongs to and must not reference other objects. If you have only managed links, you do not need (and should not) implement a destructor. You only want this to handle unmanaged resources. Since there is some cost to having a destructor , you should only implement this on methods that consume valuable, unmanaged resources.

- Ten pitfalls in C # for C ++ programmers

The article does not examine this in more detail, but what are the costs associated with using a destructor in C #?

Note: I know about the GC and that the destructor is not called at reliable times, that everything is in order, is there anything else?

+3
source share
5 answers

Any object that has a finalizer (I prefer this term over a destructor to emphasize the difference from C ++ destructors) is added to the finalizer queue. This is a list of references to objects that have a finalizer that must be called before they are deleted.

, GC (f-) . , , finalizer .

, , , GC.

, , , . , , .

+8

, , . , .

, - , .

+6

Guffa JaredPar , , , , #.

, , , ( ) . , , .

+3

Guffa . Java, .

.net , GC.SuppressFinalize. .net ( Java).


Below is a graph of the results - there are no better labels on it ;-). "Debug = true / false" refers to an empty and simple finalizer:

~ConditionalFinalizer()  
{  
    if (DEBUG)  
    {  
        if (!resourceClosed)  
        {  
            Console.Error.WriteLine("Object not disposed");  
        }  
        resourceClosed = true;  
    }  
} 

"Suppress = true" refers to a call to GC.SuppressFinalize in the Dipose method.

Summary

For .net, removing an object from the finalizer queue by calling GC.SuppressFinalize is half the cost of leaving the object in the queue.

DotnetPerformance2_thumb% 5B2% 5D.png

0
source

Source: https://habr.com/ru/post/1704246/


All Articles