Foundations
Heap memory in the frame
A frame runs the same code many times a second. Each new, malloc or growing container in that code asks the heap for memory, every frame. This page explains what that costs, where such allocations hide, and the simple tools that remove them: keep a container's capacity, use an arena, free big blocks on another thread. And it shows why you measure before you build any of them. The last part shows what RASM measured and changed.
In short
- A small allocation is fast (about 0.1 µs), but takes a lock and has no fixed cost. Many of them every frame add up and make the frame time uneven.
- A big block (above about half a MiB) comes from the operating system. Freeing it gives the pages back, which costs 0.15 to 0.3 ms for a few MiB: a lot in a 16 ms frame.
- Allocations hide in containers that lose their capacity, long strings, copies of structs with strings, callbacks with big captures and map inserts.
- Keep the capacity: clear() or swap a list instead of moving it away. After the first frames, it allocates nothing.
- An arena (linear allocator) hands out memory by moving a pointer and forgets it all at the end of the frame. It pays off for many small temporary objects; not when the data already lives in reused containers.
- Free big blocks on a worker, and count the memory as returned once it is freed.
- Measure first: count the allocations of a frame and find their call sites, then fix only those.
1The problem: a frame that allocates
Code that runs once per frame looks harmless: a list of the objects that moved, a line of text for the screen, a copy of a texture's description. Each of them may ask the heap for memory. Look at one frame of a city with 5000 moving cars, where the list of moved cars is built again each frame.
Each allocation is cheap alone. The trouble is what they do together:
Time that adds up
Thousands per frame cost real time, in code that seems to do nothing.
Uneven frames
Most calls are fast. Now and then one is slow: the heap asks the operating system for pages, or merges free blocks.
A shared lock
The heap is shared by all threads. The frame's thread can wait for workers that allocate at the same time.
2Small blocks and big blocks
A general heap treats sizes in two ways. Small blocks come from pages it already holds, through free lists. Big blocks come straight from the operating system, and go straight back to it when they are freed.
3What it costs
Numbers from one machine (Windows, 24 threads, Release build), measured by timing every new and delete of a running program (section 8):
4Where allocations hide
Few frame allocations are a visible new. Most come from a container or a library type that allocates for you:
A list moved away
b = std::move(a) takes the buffer of a. Next frame, a grows again from 0.
A long string
A short text fits inside the string (15 characters in Microsoft's library, 22 in libc++). A longer one, built every frame, allocates every frame.
A copy of a struct
A getter that returns a description by value copies its name string, to read one field.
A callback
A std::function whose captures do not fit its small inline space puts them on the heap.
A map insert
Node-based maps and lists allocate a node per insert. Erase and insert again each frame, and it allocates each frame.
The plain fix
Reuse the container, write text into a stack buffer, return a const&, build the string only when it is needed.
5Keep the capacity
A list that is filled again every frame needs no new memory after the first frames, if it keeps its buffer. clear() empties a std::vector but keeps its capacity. Moving it away does not.
Move it away
settling = std::move(moved);
moved.clear();
Swap, then clear
std::swap(settling, moved);
moved.clear();
With a swap, the two lists trade buffers. Each one grows once, in the first two frames, and then both are big enough. Try it: change how many items a frame adds, and how the list is handed on.
- A list that never shrinks
- A burst of 1 million items leaves 1 million items of capacity. That is the point; if memory matters, shrink it after the burst (shrink_to_fit), not every frame.
- A local container in a frame function
- It is freed at the end of the function and grows again next frame. Make it a member, or reserve its known size.
- reserve every frame
- It is free when the capacity is already there. Without capacity it is still one allocation per frame: better than a ladder, worse than none.
6Arenas: one pointer per frame
An arena, or linear allocator, owns one big block. To allocate, it moves a pointer forward. It never frees one object: at a known point, the end of the frame, it moves the pointer back to the start, and everything is gone at once.
When it pays
Many small objects of mixed types made and dropped in every frame: command lists built per object, scratch arrays of a pass, strings for a debug overlay.
When it does not
The data already lives in a few containers that keep their capacity. They allocate nothing after the first frames; an arena would add code and nothing else.
The risk
A pointer kept past the reset reads next frame's data. Nothing catches it: the memory is still valid, only wrong.
7Big blocks: free them on another thread
A loader decodes an image on a worker into a new block of several MiB. The frame's thread copies it into an upload buffer and frees it. The copy is the useful part; the free returns the pages and holds the frame's thread for a fraction of a millisecond. Move the free to a worker: hand it the last reference.
If a memory budget holds loads back (backpressure), decide when the freed bytes count as returned:
When the free is handed on
New loads start while the old data is still in memory. The real peak goes over the budget.
When the free is done
The free job frees, then gives the bytes back. The budget never counts data as gone while it is still in memory.
- The free job never runs at shutdown
- A pool that stops drops its queue. The dropped job's captures must still be destroyed, which frees the memory then, on the thread that stops the pool. Never let a queued free leak.
- The worker is not the last owner
- With shared ownership, the memory goes when the last reference goes. Hand the worker the last one, or the free happens wherever the other reference dies.
- Reuse instead of free
- A pool of big buffers also saves the page faults of the next decode. It is more code, with its own budget; do it only if the faults show up in a profile.
8Measure first
Guessing where allocations come from fails often: they hide in library types (section 4). Count them instead.
- countReplace the global operator new and delete in a test build. Count calls, bytes and the time inside them, per thread and per frame.
- findFor a window of steady frames, record each allocation's call stack. Sort the stacks by count and by time, and name them with the debug symbols.
- fixFix only the stacks that matter, with the plainest tool: keep a capacity, a stack buffer, a reference, a free on a worker.
- guardKeep a test that renders a few steady frames and fails if the frame's thread allocates.
9In RASM
RASM measured first, with a counting hook and Tracy (Release, headless, RTX 3060, 24 threads). Steady frames already allocated little: the render graph is built once, and the GPU tables and draw lists keep their vectors. Four causes made every steady allocation, and the big frees of loads cost a millisecond per load frame. Those were fixed. A per-frame arena and pool allocators for the registries were not needed: there was no transient data left for an arena, and the registries are already handle pools over vectors.
| Steady frame (main thread) | allocations before → after | bytes per frame | where they came from |
|---|---|---|---|
| 05_city | 24 → 0 | 259 KB → 0 | the moved-entity list lost its capacity in syncGpuScene (22); the "LOD draws" line of the RASM window (2) |
| 11_many_lights | 18 → 0 | 51 KB → 0 | the moved-entity list |
| 07_lights | 6 → 0 | 176 B → 0 | beginPass copied a TextureDesc to read cube (5) |
| 15_debug_ui (UI on) | 2 → 0 | 96 B → 0 | getUiTexture copied a TextureDesc; the moved-entity list |
| a debug view | 1 → 0 | 32 B → 0 | prepareSceneView built its defines string every frame |
| 09, 00, 02, 03, 06, 10 | 1 to 7 → 0 | tiny | the same sites |
| 01, 04, 08, 12, 13, 14 | 0 → 0 | 0 | — |
The steady frame time did not change (05_city 1.36 → 1.35 ms, GPU bound): 5 µs of 1.36 ms is noise. The win is a frame whose cost does not depend on the heap. Two cases still allocate, both on purpose: Dear ImGui bakes a glyph the first time it draws it and grows its vertex buffers when the text gets longer; and creating or destroying objects allocates (in 17_streaming about 40 a frame, most of them the example's own mesh building, about 7 in the engine's range allocators: a few µs a frame).
MeshLoadJob), an environment's image, a texture's own decode (TextureLoadJob) or a glTF texture's levels, and a finished load that is dropped (dropPendingLoad).beginFrame self time per burst frameTracy; the budget copies more insteadWhere RASM follows this page, and where it differs
| Part | This page | RASM |
|---|---|---|
| Keep the capacity | swap, then clear | syncGpuScene swaps settlingEntities and movedEntities. |
| Strings | a stack buffer | drawCullingSection writes the "LOD draws" line into a char[160]; prepareSceneView builds a debug view's defines only while a pipeline is missing. |
| Copies | return a reference | RenderContext::getTextureDesc returns a const TextureDesc&, valid until the texture is destroyed, its render target is resized or the swapchain is made again. |
| Arenas | for many small temporary objects | Not used: measured, nothing needs one. |
| Big frees | on a worker, bytes back after the free | AssetLoader::Impl::freeOnWorker pushes a child job with the last reference; it frees, then calls WorkerPool::releaseBytes. A stopping pool frees on the caller. WorkerPool::dropLoad returns a dropped finished load's bytes, so they follow its free too. One exception: a glTF image that several textures share gives its bytes back with the first of them (P26). |
| Guard | a test of steady frames | rasm_image_tests renders 2 more frames after each test's readback, then counts 4 frames: any allocation on the main thread fails the test, with the count, the bytes and the size of the first. Windows only, and not with AddressSanitizer (allocationCountingWorks). |
Where it lives in code
| What | Where |
|---|---|
| The moved-entity lists | Renderer::syncGpuScene, writeInstanceRows in src/renderer/gpuScene.cpp |
| Freeing load results | AssetLoader::Impl::freeOnWorker, dropPendingLoad, finishReadyLoads in src/assets/assetLoader.cpp; finishMeshLoad in src/assets/mesh.cpp |
| The worker pool's child queue | WorkerPool::pushChild, shutdown in src/core/workerPool.cpp |
| The guard | startCountingAllocations, stopCountingAllocations in tests/image/allocationCounter.cpp; renderTest in tests/image/imageTests.cpp |
| Tests | tests/workerPoolTests.cpp: a child job's captures are freed whether it runs, is dropped or comes after shutdown |
- A steady frame makes no heap allocation on the main thread. A new per-frame list is a member that keeps its capacity, never a local or a moved-away one.
- Do not keep a
getTextureDescreference across a destroy, a resize or a new swapchain. - A finished load's data is freed through
freeOnWorker, and its budget bytes go back after the free. - Build an arena or a pool only when a measurement shows the need (
P27,P26in the code review).
Further reading
- Microsoft's documentation of the Windows heap (HeapAlloc, the low-fragmentation heap) and of VirtualAlloc and VirtualFree; the glibc manual on mallopt and M_MMAP_THRESHOLD.
- The C++ standard on replacing the global operator new, and on std::vector's capacity after clear and move.
- Tracy's manual: memory profiling and call stacks.
- Related guides: job systems and worker pools, streaming assets, one frame, step by step, GPU timing and frame statistics.