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.

frame one frame, 1.36 ms 22 allocations: the moved list grows 2: a string buffer … 5395 items Each step: a new, 1.5 times bigger block, a copy of the items, a free of the old block. At the end of the frame the list is moved away, so the next frame starts again from 0. 22 allocations and 259 KB per frame; with 16-byte items
Nothing here is wrong in a function that runs once. In a frame it runs over 700 times a second: about 17 000 allocations and 190 MB of heap traffic per second, for a list whose size hardly changes.

Each allocation is cheap alone. The trouble is what they do together:

adds up

Time that adds up

Thousands per frame cost real time, in code that seems to do nothing.

spike

Uneven frames

Most calls are fast. Now and then one is slow: the heap asks the operating system for pages, or merges free blocks.

heap lock main worker

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.

Small: from the heap's own pages free list: the free blocks, linked alloc and free: about 0.1 µs, no system call Big: from the operating system 5.6 MiB = 1400 pages OS free: unmap the pages, and every core drops them from its address cache (TLB) 0.15 to 0.3 ms per free Where "big" starts depends on the heap: about 512 KiB in the Windows heap, 128 KiB by default in glibc's malloc (it grows with use). The first write to fresh pages also costs a page fault per page: whoever writes them first pays it.
A big block is not slow to use, only to get and to give back. A thread that decodes an image into a new 5 MiB block pays the page faults; the thread that frees it pays the unmap.

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):

≈ 0.1 µsa small allocation or free24 allocations + 24 frees took 5.4 µs a frame
0.15–0.3 msfreeing a big block of a few MiB254 frees of 5.6 MiB on average: 67.6 ms
≈ 1.2 msa load frame's big frees4 or 5 decoded images freed per frame
0.4 %24 small allocations of a 1.36 ms framenoise, until there are thousands
So two different problems Small allocations in a steady frame cost little time but make the frame's cost depend on the heap. Big frees on the frame's thread cost a millisecond at once. They have different fixes.

4Where allocations hide

Few frame allocations are a visible new. Most come from a container or a library type that allocates for you:

capacity 0

A list moved away

b = std::move(a) takes the buffer of a. Next frame, a grows again from 0.

"Draws 812" "LOD draws 801 7 2 1"

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.

desc name a copy

A copy of a struct

A getter that returns a description by value copies its name string, to read one field.

callback captures

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.

char text[160] on the stack

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.

frame 1frame 2frame 3 the same growth, every frame

Move it away

settling = std::move(moved);
moved.clear();
frame 1frame 2frame 3 nothing both lists keep their buffers

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.

Start with "moved away" and look at the allocations in frame 10. Then pick "swap + clear". Then change the growth factor: 1.5 is Microsoft's standard library, 2 is libstdc++ and libc++.
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.

A B C D next = next + size end of frame: next = start No free list, no lock (one arena per thread), no per-object free. Each object's lifetime must end with the frame.
An arena turns many allocations into one pointer move each. It also fixes the order of the bytes: objects made together lie together in memory.

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.

a reused buffer

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.

used after the reset

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.

Free on the frame's thread main copy free copy free copy free the frame's load budget Free on a worker main copy copy copy copy worker free free free free
The frame is no shorter, because a load budget sets its length. But it copies more in the same time, so the loads end sooner.

If a memory budget holds loads back (backpressure), decide when the freed bytes count as returned:

budget over

When the free is handed on

New loads start while the old data is still in memory. The real peak goes over the budget.

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.

  1. countReplace the global operator new and delete in a test build. Count calls, bytes and the time inside them, per thread and per frame.
  2. 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.
  3. fixFix only the stacks that matter, with the plainest tool: keep a capacity, a stack buffer, a reference, a free on a worker.
  4. guardKeep a test that renders a few steady frames and fails if the frame's thread allocates.
Count only your own thread A replaced operator new on Linux and macOS also serves the shared libraries, such as the GPU driver and the validation layer. A test that counts their allocations fails for reasons outside your code. On Windows each DLL has its own operator new, so only the program's own code is counted. Count on one thread only, with a thread_local flag, so the workers do not count either.

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 → afterbytes per framewhere they came from
05_city24 → 0259 KB → 0the moved-entity list lost its capacity in syncGpuScene (22); the "LOD draws" line of the RASM window (2)
11_many_lights18 → 051 KB → 0the moved-entity list
07_lights6 → 0176 B → 0beginPass copied a TextureDesc to read cube (5)
15_debug_ui (UI on)2 → 096 B → 0getUiTexture copied a TextureDesc; the moved-entity list
a debug view1 → 032 B → 0prepareSceneView built its defines string every frame
09, 00, 02, 03, 06, 101 to 7 → 0tinythe same sites
01, 04, 08, 12, 13, 140 → 00—

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).

main fill texture fill texture fill texture fill texture frame freeOnWorker: last reference + bytes WorkerPool children queue (runs before new loads) workers free the decoded data then releaseBytes(bytes) A pool that is stopping drops the job: its captures are destroyed then, so the memory is freed, never leaked.
The same path frees a finished mesh's CPU data (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).
70.5 → 3.5 msmain thread in new and delete, 300-image burstbig frees moved to the workers
1.1 → 0.05 msbeginFrame self time per burst frameTracy; the budget copies more instead
413 → 335 msburst load timetools/load_bench.py, median of 5
184 → 176 msSponza load timemain thread: 12.9 → 0.7 ms in new and delete

Where RASM follows this page, and where it differs

PartThis pageRASM
Keep the capacityswap, then clearsyncGpuScene swaps settlingEntities and movedEntities.
Stringsa stack bufferdrawCullingSection writes the "LOD draws" line into a char[160]; prepareSceneView builds a debug view's defines only while a pipeline is missing.
Copiesreturn a referenceRenderContext::getTextureDesc returns a const TextureDesc&, valid until the texture is destroyed, its render target is resized or the swapchain is made again.
Arenasfor many small temporary objectsNot used: measured, nothing needs one.
Big freeson a worker, bytes back after the freeAssetLoader::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).
Guarda test of steady framesrasm_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

WhatWhere
The moved-entity listsRenderer::syncGpuScene, writeInstanceRows in src/renderer/gpuScene.cpp
Freeing load resultsAssetLoader::Impl::freeOnWorker, dropPendingLoad, finishReadyLoads in src/assets/assetLoader.cpp; finishMeshLoad in src/assets/mesh.cpp
The worker pool's child queueWorkerPool::pushChild, shutdown in src/core/workerPool.cpp
The guardstartCountingAllocations, stopCountingAllocations in tests/image/allocationCounter.cpp; renderTest in tests/image/imageTests.cpp
Teststests/workerPoolTests.cpp: a child job's captures are freed whether it runs, is dropped or comes after shutdown
Keep these true
  • 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 getTextureDesc reference 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, P26 in the code review).

Further reading