The Mini Object Pool
The idea of the mini-pool is that it’s really mini: it holds by default at most… one entry!
But that allows it to be lightweight and involve just a cheap atomic lock through the InterlockedExchangePointer function for thread-safety.
Here is a minimalist implementation:
var vPool : Pointer; function AllocFromPool : TWorkClass; begin Result := InterlockedExchangePointer(vPool, nil); if Result = nil then Result := TWorkClass.Create; end; procedure ReturnToPool(var obj : TWorkClass); begin if obj=nil then Exit; obj.Clear; // or whatever restores TWorkClass to default state if vPool=nil then obj:=InterlockedExchangePointer(vPool, obj); obj.Free; end;
This is quite simple, but already when applied to a very simple class like TList, the allocation/release cost can be divided up to 15 times if you use the InterlockedExchangePointer from the Windows unit, and up to 40 times if you use the one from the dwsXPlatform unit.
Ideally, rather than isolated functions, you’ll probably want to use a static class function for AllocFromPool, and a regular method for ReturnToPool (cf. f.i. the TWriteOnlyBlockStream class in DWScript‘s dwsUtils unit).
Just don’t forget to add to your unit finalization clause something like
or you’ll be leaking one instance at shutdown.