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:

// C#
TVec a = null, b = null, c = null;
TMtxVec.CreateIt(out a, out b, out c);
try {
    a.Size(1000);
    b.Size(1000);
    a.RandUniform();
    c.Sin(a);
    c.Add(b);
} finally {
    TMtxVec.FreeIt(ref a, ref b, ref c);
}

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 C#, new Vector() and new TVec() are equivalent — both allocate ordinary .NET objects reclaimed by the garbage collector. There is no object cache and no CreateIt/FreeIt to manage; just use new.

Pool monitoring:

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

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