TExcelTAD
Home › Game Engine Architecture in C++ › Field Notes: Performance

Field Notes: Performance

Engine performance work has a reputation for clever tricks. In practice most wins come from a few boring habits: measuring, laying data out sensibly, not allocating in the frame, and spreading work over time. These notes collect them.

1. Measure first, then measure again

Intuition about where time goes is wrong more often than right, even for experienced engine programmers. Before changing anything, capture a profile (Profiling) of a reproducible scene, find the biggest zone, fix that, and capture again with the same scene and camera path. Keep the numbers in the commit message.

Measuring also tells you when not to optimise. The program below counts the pair tests of a brute-force collision check against a uniform grid. The grid is the "clever" algorithm, but it has a fixed cost of its own (clearing and filling cells):

cpp · try it yourself
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>

struct P { float x, y; };

std::vector<P> makePoints(int n) {
    std::vector<P> pts;
    std::uint32_t s = 7;
    auto next = [&] { s = s * 1664525u + 1013904223u; return float(s >> 8) / float(1 << 24); };
    for (int i = 0; i < n; i++) pts.push_back({next() * 100, next() * 100});
    return pts;
}

long bruteForce(const std::vector<P>& pts) {
    long ops = 0;
    for (std::size_t i = 0; i < pts.size(); i++)
        for (std::size_t j = i + 1; j < pts.size(); j++) ops++;          // one distance test per pair
    return ops;
}

long grid(const std::vector<P>& pts, int cells) {
    long ops = cells * cells;                                            // clear the cells
    std::vector<std::vector<int>> g(cells * cells);
    for (int i = 0; i < int(pts.size()); i++) {                          // insert
        int cx = std::min(cells - 1, int(pts[i].x / 100 * cells)), cy = std::min(cells - 1, int(pts[i].y / 100 * cells));
        g[cy * cells + cx].push_back(i); ops++;
    }
    for (int cy = 0; cy < cells; cy++)                                   // test each cell against itself and 4 neighbours
        for (int cx = 0; cx < cells; cx++) {
            const auto& a = g[cy * cells + cx];
            for (std::size_t i = 0; i < a.size(); i++)
                for (std::size_t j = i + 1; j < a.size(); j++) ops++;
            const int nb[4][2] = {{1, 0}, {-1, 1}, {0, 1}, {1, 1}};
            for (auto& d : nb) {
                int nx = cx + d[0], ny = cy + d[1];
                if (nx < 0 || ny < 0 || nx >= cells || ny >= cells) continue;
                ops += long(a.size() * g[ny * cells + nx].size());
            }
        }
    return ops;
}

int main() {
    std::cout << std::setw(6) << "n" << std::setw(12) << "brute" << std::setw(12) << "grid 20x20" << "\n";
    for (int n : {10, 50, 200, 1000, 5000}) {
        auto pts = makePoints(n);
        std::cout << std::setw(6) << n << std::setw(12) << bruteForce(pts) << std::setw(12) << grid(pts, 20) << "\n";
    }
}
     n       brute  grid 20x20
    10          45         410
    50        1225         472
   200       19900        1033
  1000      499500       11828
  5000    12497500      268310

With 10 objects, brute force does a ninth of the grid's work (45 tests against 410 operations), and it is simpler to debug. The crossover sits between 10 and 50 objects for this 20×20 grid; past it the grid wins by orders of magnitude. Counting (or timing) on your real object counts tells you which side you are on.

2. Data layout beats clever algorithms

Modern CPUs are fast at arithmetic and slow at fetching memory: a cache miss to main memory costs on the order of a hundred cycles or more. Code that walks contiguous arrays of exactly the data it needs (see Cache Behavior: AoS vs SoA) usually beats a theoretically better algorithm that chases pointers through a tree or a linked list. Before reaching for a smarter algorithm, ask: is the data packed, is it touched in order, and does the loop read fields it doesn't use?

3. Don't allocate in the frame

General-purpose new/malloc takes locks, fragments memory, and has unpredictable cost; a frame that allocates thousands of small objects will spike. Reuse containers (clear() keeps capacity), reserve up front, use per-frame linear allocators for temporary data and pools for objects that come and go. Counting allocations per frame is easy and deterministic:

cpp · try it yourself
#include <cstdlib>
#include <iostream>
#include <new>
#include <string>
#include <vector>

static long gAllocs = 0;
void* operator new(std::size_t n) { gAllocs++; if (void* p = std::malloc(n)) return p; throw std::bad_alloc(); }
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

struct Hit { int entity; float distance; };

std::vector<Hit> queryNaive(int count) {                     // returns a fresh vector every call
    std::vector<Hit> hits;
    for (int i = 0; i < count; i++) hits.push_back({i, float(i)});
    return hits;
}

void queryInto(std::vector<Hit>& out, int count) {           // caller-owned, reused buffer
    out.clear();
    for (int i = 0; i < count; i++) out.push_back({i, float(i)});
}

int main() {
    const int frames = 60, queriesPerFrame = 50, hitsPerQuery = 20;

    long before = gAllocs;
    for (int f = 0; f < frames; f++)
        for (int q = 0; q < queriesPerFrame; q++) { auto hits = queryNaive(hitsPerQuery); (void)hits; }
    std::cout << "fresh vector per query: " << gAllocs - before << " allocations in " << frames << " frames\n";

    before = gAllocs;
    std::vector<Hit> scratch;
    scratch.reserve(64);
    for (int f = 0; f < frames; f++)
        for (int q = 0; q < queriesPerFrame; q++) queryInto(scratch, hitsPerQuery);
    std::cout << "reused scratch buffer:  " << gAllocs - before << " allocation in " << frames << " frames\n";

    before = gAllocs;
    for (int f = 0; f < frames; f++) { std::string label = "Enemy_" + std::to_string(f) + "_health_bar_text"; (void)label; }
    std::cout << "string building per frame: " << gAllocs - before << " allocations (beyond the small-string buffer)\n";
}
fresh vector per query: 18000 allocations in 60 frames
reused scratch buffer:  1 allocation in 60 frames
string building per frame: 60 allocations (beyond the small-string buffer)

The naive query allocates every time its vector grows (six times for 20 elements with libstdc++'s doubling), 18,000 allocations in a second of gameplay. The reused buffer allocates once. Strings longer than the small-string buffer (15 characters in libstdc++) allocate too, which is why engines use interned string IDs and fixed buffers for per-frame text.

4. Budget per subsystem and watch the worst frame

Give each subsystem a slice of the frame (for example at 60 FPS: gameplay 3 ms, physics 2.5 ms, animation 2 ms, render submission 4 ms, audio 0.5 ms, slack for spikes) and show the budgets in the debug overlay. Track the 99th percentile frame time, not the average: players notice the hitch, not the mean.

5. Spread work over frames

Not everything must happen every frame. Path requests, AI decisions for distant enemies, LOD selection, streaming checks, reflection probe updates and UI layout can be time-sliced: process at most N per frame from a queue, or update distant objects every 4th frame (staggered by entity index so the load is even).

6. Know whether you are CPU- or GPU-bound

If the CPU spends its time waiting in SwapBuffers, vkQueuePresentKHR or a fence, the GPU is the bottleneck and CPU optimisations won't change the frame rate. Shrink the render resolution: if the frame gets faster, you are pixel-bound on the GPU. Use RenderDoc, PIX or Nsight for GPU work.

7. Threads last, not first

A job system helps only once the work is cleanly split into independent pieces with explicit inputs and outputs. Parallelising tangled code adds locks, races and bugs while the frame barely improves. Fix the data flow, then parallelise the hot loops (Job Systems), and watch for false sharing.

8. Profile release builds on the target hardware

Debug builds have different hot spots (unoptimised STL, iterator debugging, asserts). A development machine with 16 cores and a high-end GPU hides problems that a handheld or a five-year-old laptop shows immediately. Keep a "min-spec" machine in the office and in CI.

9. Load times are performance too

Players wait for loading more than for any single frame. Measure it with the same seriousness: cooked binary assets, fewer and larger files, asynchronous I/O, decompression on worker threads, and no per-object std::string path lookups during load.

Test yourself

In the collision example, why did brute force beat the grid for 10 objects?

  1. Brute force is O(n log n)
  2. The grid has a fixed overhead (clearing and visiting all cells) that dominates when there are few objects
  3. The grid had a bug
  4. Small arrays fit in the GPU

What is the simplest fix for a function that returns a new std::vector of results on every call in a hot loop?

  1. Use std::list
  2. Let the caller pass a reused buffer that is cleared (keeping its capacity) each call
  3. Return by pointer
  4. Call shrink_to_fit

The CPU timeline shows most of the frame spent waiting in the present call. What does that suggest?

  1. The CPU is the bottleneck
  2. The GPU is the bottleneck, so CPU optimisation won't raise the frame rate
  3. There is a memory leak
  4. Threads are deadlocked