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
In C++ GetCapacity() returns the allocation floor set with SetCapacity (0 by default), not the size of the current allocation: after a.Size(1000) on a new Vector, GetLength() is 1000 and GetCapacity() is 0. Sizing never allocates less than Capacity. Without a floor, an object created with new TVec() reallocates when its size changes, while an object from the object cache (Vector, CreateIt) reuses its pre-allocated block for every size that fits (Controller->SetVecCacheSize sets that block size).
- When you call
Size(N), if N <= Capacity, no reallocation occurs — only Length changes
Example:
a.SetCapacity(1200); // floor: Size() never allocates less than 1200 elements
a.Size(1000); // allocates room for 1200 elements, Length = 1000
a.Size(500); // Length = 500, the memory is kept (no realloc)
a.Size(1200); // Length = 1200, still fits (no realloc)
a.Size(100); // Length = 100, the memory is kept
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, keep the memory
a.SetCapacity(0); // no allocation floor (the default)
a.SetCapacity(10000); // from now on, every allocation Size() makes holds at least 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.