Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


cons of GC


c# using statement


finalize dispose close

Question

Difficulty Level: 3.8

  • Every object in C# is derived from the object class and the object class has a finalizer method. Finalizer methods are known to slow down garbage collection. Why does the Finalize method slow down the garbage collection in C# and is the finalize method called for every object in C# since it inherits this method from the object class ?

Solution

Explanation Quality:3.5

The Finalize method is used to release native resources held by an object say a network socket or a file handle. Let's start by answering the second part of the question. When the CLR detects that the finalize method for an object is the one inherited from the object class the CLR runtime makes sure not to invoke it on the object.

The first part of the question asks if the finalize object does cause the slowdown of the garbage collection of an object. This is true because of the additional steps required in executing the finalize method. Here's what you need to remember

Whenever an object with a finalize method is initialized, it is placed on a special list of all objects with finalize methods. When the object with a finalize method isn't pointed to by any root in the application, it becomes a candidate for garbage collection. When the GC runs it picks the reference to this object and places in a queue called the freachable queue. Objects placed on this queue must have their finalize method called before being collected by a CLR thread. Since now there's a reference in the freachable queue pointing to the object, it is no more considered garbage and ignored by the GC. Next, the CLR thread will call the finalizle methods of the objects and remove the referece to them from the freachable queue. The next time the GC runs, since there's no reference to these objects anymore, they will be collected.

This extra overhead in calling the finalize method is really the reasons for the slowdown and generally finalize methods are to be avoided. To deterministically clean-up resources use the dispose pattern.

Note that within an object's finalize method you shouldn't try to access an object that also defines the finalize method, since the order of the execution of the finalize methods of the two objects is not known, it could be possible that the other object's finalize method has already been called.

Note that a C# Finalizer is sometimes taken to be an equivalent of the destructor in C++ since the syntax to define the two is very similar, however the two aren't similar. One stark difference is that Finalize method for an object is called by the garbage collector in CLR but when the finalize method would be called is anyone's guess. It's dependent on the GC and isn't deterministic. However in case of C++ destructors, the call to the destrcutor is deterministic.

 

 




Previous Next