Answer» Both dispose() and finalize() methods are used for unallocating and freeing up resources but:
- dispose() method is called explicitly by the user, whereas finalize() method is called the system’s garbage collector at the end of execution.
- dispose() method is defined in the IDisposable interface, whereas the finalize() method is defined in the Object class.
- dispose() method is a part of the developer’s code, whereas finalize() method is a system-defined default method and not a part of the developer’s code.
| BASIS FOR COMPARISON | DISPOSE( ) | FINALIZE( ) |
|---|
| Definition | dispose() method is defined in IDisposable interface. | finalize() method is defined in java.lang.object class. |
|---|
| Syntax |
public void dispose( ){ // Dispose code here } |
protected void finalize( ){ // finalization code here } |
|---|
| Invoked | dispose() method is invoked by the user. | finalize() method is invoked by the garbage collector. |
|---|
| Purpose | dispose() method is used to free unmanaged resources upon invoking. | finalize() method is used to free the unmanaged resources when invoked by the garbage collector. |
|---|
| Implementation | dispose() method is implemented whenever there is a close( ) method. | Unlike dispose(), the finalize() method is implemented for freeing up unmanaged resources. |
|---|
| Access Specifier | dispose() method is declared as public. | finalize() method is declared as private. |
|---|
| Performance | dispose() method happens instantly and hence is faster. | finalize() method is slower in comparison with dispose() method and can affect the performance. |
|---|
|