delphifinalization

Is it ok not to free objects before unit unloads from memory (finalization section)?


Since the process will be killed by OS and all memory allocated will be recycled anyway, is it OK not to free objects/resources in the unit finalization section?

For example,

unit Threading;

interface

implementation

  var threadpool: ThreadPool;

initialization

  threadpool := ThreadPool.Create;

finalization

  threadpool.Free; // is it OK to remove this?

end.

Solution

  • Since the process will be killed by OS and all memory allocated will be recycled anyway, is it OK not to free objects/resources in the unit finalization section?

    Yes, it is, probably. The system will clean up resources when the process terminates.

    However, there are a couple of provisos:

    1. Most leak detection tools check that all dynamically allocated memory is destroyed by your process before it returns control to the system. What you are proposing to do renders such tools impotent.
    2. If your code is ever built into a dynamic library such as a DLL or a package, then the library can be unloaded, whilst the host process endures. This is a leak and can affect the viability of the host process.
    3. Some objects require finalization to occur, sometimes with ordering constraints. Without knowing more about your class, we can't judge that.