In this lesson, you will learn how TArray manages memory behind the scenes and how to prevent performance-heavy reallocations by pre-allocating memory.
Understanding Contiguous Memory
TArray is Unreal’s primary dynamic array. Unlike a linked list, TArray stores its elements in a contiguous block of memory. This is fantastic for CPU cache performance because the processor can easily predict and access the next item in the sequence.
However, because memory is contiguous, the array must be stored in one "solid" piece of RAM. If you add an element to an array that is already full, TArray must:
- Allocate a brand-new, larger block of memory.
- Copy every existing element from the old block to the new one.
- Deallocate (delete) the old block.
If this happens frequently while your game is running, you create "memory churn," which can cause frame stutters.
Minimizing Reallocations with Reserve
To avoid unnecessary copying, you should use the Reserve function if you have a rough idea of how many items your array will eventually hold. When you Reserve, you tell TArray to allocate enough space for X number of items upfront.
// Bad: The array reallocates memory multiple times as we add items
TArray<int32> EnemyHealths;
for(int32 i = 0; i < 100; ++i) { EnemyHealths.Add(i); }
// Good: Pre-allocate space for 100 elements to avoid reallocations
TArray<int32> EnemyHealths;
EnemyHealths.Reserve(100);
for(int32 i = 0; i < 100; ++i) { EnemyHealths.Add(i); }
By calling Reserve(100), the engine performs a single memory allocation. When you then Add() elements up to the 100th index, the array simply fills the space already provided, keeping your game running smoothly without the overhead of hidden copy operations.
Remember, Reserve does not change the Num() (the count of elements) of your array; it only changes the capacity. It is a defensive programming habit that keeps your memory management efficient and predictable.
Key Takeaway: Use TArray::Reserve() to pre-allocate memory when you know the required size, preventing costly reallocations and improving your game's performance.