Allocate objects on stack, at specified memory address, or through any memory manager

download the code and sample project. 7K zip file.

Isn't it very cool to create objects on the stack, or in a specified memory buffer, or at a fixed memory location, or even through a highly optimized memory manager?
Here we go!

procedure TestIt;
var
  lObj: TTestObject;
  I: Integer;
begin
  EnterLocalObject(TTestObject, 100);
  try
    for I := 1 to 100 do
      lObj := TTestObject.Create;
    try
      lObj.ShowMsg;
    finally
      lObj.Free;
    end;
  finally
    LeaveLocalObject;
  end;
end;
Now let's look at above piece of code.
In the function TestIt, I allocate 100 TTestObject, but I only free the last object and leave other 99 objects leaked in the memory. That seems a foolish memory leak, but if we use Denomo to check it, no memory leak is found.
What's the secret behind that?
The answer is the two magic functions, EnterLocalObject and LeaveLocalObject. EnterLocalObject can redirect to the object allocation to the local stack or any specified buffer.
These functions can break the limitation in Delphi that "objects must be allocated in the heap".

The benefit to use LocalObject:
1, Allow you to create objects on the stack. This is same as how C++ does with local objects, and even better, allocating objects on the stack is usually faster than on the heap.

2, Allow you to optimize objects allocation on purpose.
For example, if your program performs a file search option and you expect the result contains huge amount of file objects (more than 100K), you can optimize it to reduce fragment and performance by using an optimized memory manager such as I discussed here.

3, It's possible to use external storage device such as hard disk to allocate objects, then use memory mapping to return the objects as pointer. This gives you the chance to allocate huge amount objects on the disk which total memory is larger than the virtual memory size. Then you can only map the required objects to memory and leave other objects on the disk.

Write a comment

  • Required fields are marked with *
  • Security Code is case sensitive, 'A' is different with 'a'.

If you have trouble reading the code, click on the code itself to generate a new random code.
Security Code: