Object Cache: CreateIt/FreeIt Pattern

MtxVec maintains a pre-allocated object pool (cache) for TVec and TMtx objects. CreateIt/FreeIt borrow and return objects from this pool — they do not allocate/free memory.

Why use CreateIt/FreeIt:

  • Objects are pre-allocated at startup → near-zero allocation cost
  • Pool objects have pre-allocated memory → no heap allocation for small sizes
  • Essential for block processing loops where objects are created/destroyed rapidly
  • Used with TVec/TMtx (pool-managed types), not with Vector/Matrix (value types)

Basic pattern:

var a, b, c: TVec;
begin
    CreateIt(a, b, c);   // borrow 3 objects from pool
    try
        a.Size(1000);
        b.Size(1000);
        a.RandUniform;
        c.Sin(a);
        c.Add(b);
    finally
        FreeIt(a, b, c);   // return to pool (not freed from memory)
    end;
end;

Rules:

  1. Always pair CreateIt with FreeIt in try/finally
  2. Never mix CreateIt objects with regular constructor objects
  3. CreateIt objects are for LOCAL variables only — do not store in fields
  4. FreeIt does not destroy the object — it returns it to the pool for reuse
  5. After FreeIt, the variable is set to nil — do not use it

When to use what:

ScenarioUseWhy
General codeVector / MatrixAutomatic lifetime, operator support
Block processingCreateIt/FreeIt with TVec/TMtxL1 cache discipline, fast pool reuse
Temporary in tight loopCreateIt/FreeItNo GC pressure, predictable lifetime
Fields / propertiesVector / MatrixAutomatic management, no manual free

In Delphi, Vector, Matrix, VectorInt, and MatrixInt all use this object cache (CreateIt/FreeIt) pattern internally — the value type borrows an object from the pool on use and returns it automatically. Choosing them is not avoiding the pool; it is using it without the manual bookkeeping. (This applies to Delphi only — in C# these value types are managed by the .NET garbage collector, not the object cache.)

Pool monitoring:

// Check for leaks — should be 0 after all FreeIt calls
Controller.Pool[ThreadIndex].VecCacheUsed
Controller.Pool[ThreadIndex].MtxCacheUsed

Debug mode: Compile with Assertions ON to disable pooling — CreateIt/FreeIt become real alloc/dealloc, enabling FastMM leak detection.