What it actually is just a dynamic array, but a very efficient dynamic array. And unlike standard dynamic arrays this class guarantees that if you put an item in it the pointer to the item stays the same all the time no matter how many items you add after this. The trick is to allocate new memory in fixed sized blocks which can reside sufficient amount of items.

The important moment which often lacks of attention here is the AllocMem function. Everybody just use the standard GetMem(var p: pointer; Size: NativeInt) function for this. But I discovered that the standard delphi memory manager deals very bad with large blocks of memory. It tends to not free the virtual address space (VAS) after you call FreeMem. For example, In SprutCAM when a user generated a toolpath on a complex part and a massive amounts of memory were allocated for temporal data structures needed in the calculation process and than the user hit the reset button, the VAS which was allocated during the calculation process was not freed. The software just consumed more and more memory with every new toolpath generation.

The solution is to use the Win32 API VirtualAlloc/VirtualFree functions. Unfortunately the minimum size of a block which can allocate the VirtualAlloc function is 64kbytes, and this is too much for our needs. So we need a memory manager for a memory manager) which will split 64kbytes blocks into smaller chunks. I chose the size of 1Kb, which is big enough to reside such data as points, triangles etc, and small enough to not waste too much space if the number of used items in an array is small.

The class works the following way. With VirtualAlloc we allocate a block of 64kbytes and put it into fFreeBlocks, in the end of the block we store a 64bit mask every bit of which says which one of 64 block pages are currently free (we initialize it with Int64(-1)) . If the bit mask becomes zero in the AllocMem function it means the whole block is used and we remove it from the fFreeBlocks array, if the int64(mask) becomes –1 in the FreeMem function it means the whole block is free and we release it using the VirtualFree function.