From what I understand, empty methods are compiled, but not actually called: In .NET, will empty method calls be optimized out?
I was also reading http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx:
Empty destructors should not be used. When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
Does that mean that with an empty destructor, an entry is still created in the Finalize queue, but the JIT will prevent calling the method?
Normal empty methods (or other short methods like most getters and setters) are optimized by the JIT by inlining them in the compiled code: where a call to the method would normally appear, the whole body of the method is placed instead.
There are many cases where inlining is not worth it from performance perspective and so the compiler doesn't inline them, primarily when the method is longer than just few instructions.
There are some cases when inlining is not possible, like recursive or virtual methods. And since a finalizer (also known as destructor) is actually just overriden virtual method object.Finalize(), the compiler just can't inline it, so the method is actually called, even if it is empty.
But the performance hit from calling a method is tiny. The overhead required to process the finalizer by the GC is much bigger and so you shouldn't create classes with empty finalizers, regardless of inlining. This is the reason why you should use GC.SuppressFinalize() when implementing the Dispose pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With