Reputation:
We know that when a type override Finalize method, it must survive the garbage collection, it gets promoted to another generation, forcing the object to live much longer than it should. This is not ideal in terms of memory consumption and is why you should avoid finalization when possible.
But isn't that all type implicitly derived from Object
, and Object
does have a default Finalize method, so CLR should consider all types have Finalize method and therefore all objects on the heap will get prompted to new generation, and live longer than they should?
Upvotes: 0
Views: 205
Reputation: 10573
As @canton7 said in a comment, the runtime is smart enough to know that if there are no finalizers in the instance's inheritance chain other than Object.Finalize
then it does not have to mark the instance for finalization. The relevant part of the documentation is:
The
Object
class provides no implementation for theFinalize
method, and the garbage collector does not mark types derived fromObject
for finalization unless they override theFinalize
method.
Interestingly enough, neither the C# specification nor the ECMA CLI specification enforce this behaviour. It is permitted for a conforming implementation of the runtime to always schedule all objects for finalization. However, as you recognised in the question, this would cause an enormous overhead in garbage collection so it would be impractical.
Note: the relevant sections are §8.9 and §15.2 for the C# spec and I.8.9.6.7 of the ECMA CLI spec.
Upvotes: 3