I would like to be able to reuse memory such that Init and FMemory::Free actually just flag in_use for a pre-allocated memory pool.
is there similar functionality in any UE4 allocators ?
any example code ?
Yes, just use the Reserve(int32) function within TArray. It will pre-allocate a block of memory for you.
If you donât reserve the block of memory and you want to add in 1000 objects, the array will have to keep on resizing itself every time you exceed the bounds of the array with an âAdd()â. Most of the time, nobody will notice anything in terms of performance, but if you have say, an array of pixels for a 1024x1024 image, it would be a really good idea to reserve that block in memory. Youâd see a few ms in performance gain.
Not that Iâm aware of. If reserve isnât enough then one solution would be to pool your own array of TArrayâs somewhere and just take/put back as need be. All depends on what your wanting to do. If you need to avoid the creation/destruction cost then youâll want to store the array outside of things like loops, maybe in itâs own object pool or as a static array/global array (be wary of how this effects multithreading). And if youâd rather set flags for this datatype to determine if itâs valid or not, you can either leave the capacity as big as need by but somehow reduce the âsizeâ so that it pretends to be empty array, or wrap this TArray in your own class/struct that has the flags and functions you need. Iâm not saying what your asking for is bad, not at all. But it is a bit niche since most people canât be bothered to pre allocate memory at all. Let alone re use it.
Nukes existing elements and reallocates (if needed) to support the provided number of elements. TArray has both âNumâ and âMaxâ - it doesnât change the allocation (aka, the slow part) if you are calling Add() on an array that already has enough space allocated. Use it all the time.
Pretty rare that you need to create a custom Allocator outside of the ones which are already provided:
TDefaultAllocator<> - Allocates on-demand as needed.
TInlineAllocator<> - Allocates an initial block then adds as needed.
TFixedAllocator<> - Fixed allocation size, will assert and crash if you try to add more than the specified number of elements.
The number of elements needs to be known at compile time if you are using TInline/TFixed. Otherwise, just use Reserve() or Reset().