Memory Management and Capacity

MtxVec manages memory allocation automatically, but understanding Capacity helps optimize performance in loops that resize arrays repeatedly.

Capacity vs Length:

  • Length — number of elements currently in use
  • Capacity — total elements allocated in memory (always >= Length)
  • When you call Size(N), if N <= Capacity, no reallocation occurs — only Length changes

Example:

a.Size(1000);    // allocates ~1000 elements, Capacity >= 1000
a.Size(500);     // Length = 500, Capacity still >= 1000 (no realloc)
a.Size(1200);    // Length = 1200, Capacity grows (reallocation happens)
a.Size(100);     // Length = 100, Capacity still >= 1200

Why this matters: In loops where array size changes each iteration, Capacity prevents repeated reallocation. Once the array has grown to its maximum size, subsequent smaller sizes reuse the existing buffer.

Controlling Capacity:

a.Size(0);               // set Length to 0 but keep Capacity
a.Capacity = 0;          // force deallocation of all memory
a.Capacity = 10000;      // pre-allocate for 10000 elements

In-place operations: Methods with 0 arguments operate in-place (no allocation):

a.Sin();     // in-place: a[i] = sin(a[i]), no memory allocated
a.Sin(b);    // out-of-place: a = sin(b), a may be resized to match b

The in-place form is always fastest because it never allocates. The out-of-place form (1-arg) auto-resizes the destination, which may trigger allocation on first call but reuses Capacity thereafter.

Object cache pre-allocation:

// Configure pool at startup
Controller.SetVecCacheSize(PoolSize, PreAllocElements);
Controller.SetMtxCacheSize(PoolSize, PreAllocElements);
// PoolSize = number of TVec/TMtx objects in pool
// PreAllocElements = elements pre-allocated per object

Setting PreAllocElements to your typical array size eliminates allocation entirely for pool objects.