Concurrency[conc]

Memory Bound Code: Why Data Access Limits Speed

Abstract

A program is memory bound when its speed is limited by how quickly data can reach the processor, rather than by how quickly the processor can calculate. The delay may come from slow individual loads, limited memory bandwidth, cache misses, address translation, or contention between threads. Measure the bottleneck first, then keep frequently used data compact and nearby, access it in cache-friendly patterns, and avoid shared cache-line conflicts to improve performance.

A craftsman waits at an empty bench, hands hovering over tools, while a cart slowly approaches from a distant warehouse across vast blank space.
Figure 1 — A craftsman waits at an empty bench, hands hovering over tools, while a cart slowly approaches from a distant warehouse across vast blank space.

Picture a chef who chops faster than anyone on the line, but every ingredient sits in a storage room across town. The chef spends most of the shift waiting.

That’s what it means to be memory bound: your program’s speed is limited by how fast data reaches the processor, not by how fast it computes.

Your code can be well written and still crawl for the same reason. In this post, we’ll cover latency versus bandwidth, caches, virtual memory, diagnosis, layout fixes, and concurrency effects like false sharing.

What It Means to Be Memory Bound

A program is memory bound when data access, not arithmetic, sets its speed. That’s the wait to find before you change anything.

Waiting on data versus doing arithmetic

A compute bound program is limited by how many arithmetic steps the processor finishes. A memory bound one waits on loads and stores, so the bottleneck is data access, not math.

Copying large data is the classic trap. A game developer passes a big struct by value into a hot loop, so every call copies it and the processor spends its time moving bytes. A const reference removes the copy.

Per-load delay versus total throughput

Latency is how long one load takes to return. It hurts most when each load depends on the last, as when you walk a linked list. Bandwidth is how many bytes the memory system moves per second, and it becomes the limit when bulk work saturates it.

Latency is about how long each load waits, while bandwidth is about how much total traffic moves. Hot paths are usually latency bound. Bulk work, like filling a large buffer, tends to hit bandwidth.

Three worked examples you can follow

  • Matrix transposition. A transpose reads one way and writes the other, so one side jumps across memory on every iteration. Working in small blocks that fit the processor’s cache, its small, fast memory, keeps those jumps close.
  • Particle update loop. Fields this loop never reads still take up cache space on every pass. Splitting the hot fields into their own arrays means the loop loads only what it uses.
  • Order book update. A trading systems developer keeps price levels in linked nodes, so each lookup chases pointers. A flat, sorted std::vector keeps neighboring prices in nearby memory.

Why fixing memory pays off most

For a single-threaded program, memory access is usually the biggest lever you’ve got. Layout changes can give large speedups.

In Generic tiled layouts for high-performance multidimensional data structures, replacing standard layouts with the proposed ones gives an average speedup of over 2.2x on naive dense matrix multiplication, with peaks up to 6.7x.

Memory is the bottleneck in most C++ programs, as Drepper’s paper explains: memory access is now, and will be for some time, the limiting factor. Look at the data before you look at the math.

How Memory Levels and Caches Are Arranged

Every value your program reads sits in a memory hierarchy, and its level sets how long you wait.

Why bigger storage is always slower

A small cache near the processor answers almost at once; a large store farther away takes longer. The levels run from cache to main memory (RAM) to disk. The question isn’t how fast your processor is, but how far your data has to travel.

Stack memory is usually quick because recent data sits close together. Heap blocks can land anywhere. A game engine programmer looping over separately allocated particles pays for every pointer hop.

Packing them into one std::vector keeps the walk in order, so the loop stays fast.

Ink drawing contrasts efficient linear workflow with chaotic scattered boxes using steel blue and vermilion accents.
Figure 2 — Ink drawing contrasts efficient linear workflow with chaotic scattered boxes using steel blue and vermilion accents.

Hits, misses, and what gets evicted

Each read lands in one of two places:

  • Cache hit. The value is already cached.
  • Cache miss. The request travels to the next, slower level.

Caches move cache lines, fixed-size blocks of memory, not single bytes. Fetching one value also pulls in its neighboring data, which helps a loop that reads in order. A full cache must evict a line to make room.

Where a block may sit depends on the hardware’s mapping rules, which differ between processors.

Keeping hot data small enough for cache

Hot data is what your loop touches over and over. It should fit in cache. Once the working set (what a loop needs at once) outgrows the cache, each pass evicts lines it still needs and refetches them from a slower level.

That’s capacity thrashing, and latency climbs with every trip.

Sequential or local access wins. The hardware fetches lines ahead of your request, and you use the bytes it brings in. Random pointer chasing wastes much of every block. Keep rarely read fields out of hot structs. Smaller wins.

How Virtual Memory and Paging Work

Every pointer your program dereferences passes through a translation step you rarely see. Here’s what it does and where it can slow your code down.

How addresses map to physical memory

A pointer stores a virtual address, not the physical location in random access memory (RAM). The hardware translates one into the other using a page table that the operating system (OS) maintains, and it checks that table on every access.

Contiguous virtual memory isn’t always contiguous in RAM. An array of 10,000 integers looks like one block to your code, but its pages can sit in scattered physical memory. You never see that scatter, because the OS hides it.

How page size affects your program’s speed

Typical pages are 4 kB, or 4,096 bytes. Each translation has a cost. The processor (CPU) caches recent ones in a translation lookaside buffer (TLB). A miss forces a walk of the page table, and a page fault, where the OS steps in, is slower still.

Consider a firmware developer who hands a sensor buffer to a direct memory access (DMA) controller, which moves data without the CPU.

Aligning the buffer to a page boundary with alignas(4096) gives the device a clean start address, so the driver has one fewer edge case to handle.

A B-tree, a sorted index that databases use, reads whole nodes. Sizing each node to the page size means one node visit costs one page access, so a lookup doesn’t drag in memory it doesn’t need.

Huge pages are larger than the standard 4 kB, so each TLB entry covers far more memory. A team with a large in-memory cache can ask the OS for them, and random lookups miss the TLB less often, which means fewer translation misses on a big working set.

Finding Out Where Memory Slows You Down

Before you reshape a container, you need proof that memory is the bottleneck. A profiler shows what your code waits on, and where.

Drill down from the top-level breakdown

Top-down analysis sorts stalled cycles into buckets. Look at backend memory bound, which counts cycles spent waiting for data, and split it by source:

  • L1: smallest and fastest, next to each core
  • L2: bigger and slower, still per core
  • L3: bigger still, shared across cores
  • DRAM: dynamic random-access memory, the slowest tier

Each stall is a latency problem (one load returns too slowly) or a bandwidth problem (too few bytes move overall). The fix differs for each.

A cross-section of a workshop showing workers at different tiers, with a narrow conveyor belt bottleneck marked in vermilion.
Figure 3 — A cross-section of a workshop showing workers at different tiers, with a narrow conveyor belt bottleneck marked in vermilion.

Profilers that point to slow data

Per-level cache miss counters show which tier falls short. perf mem load sampling records addresses and latencies of sampled loads, so the report names the data, not just the function.

perf c2c flags cross-core contention: cache lines several cores keep fighting over.

Think of a developer on a message router whose L3 miss counter climbs. perf mem shows the costly loads hit one hash map’s nodes, scattered across the heap, not the parser. That’s the structure to rework.

Telling latency limits from bandwidth limits

Latency asks how long one load waits, while bandwidth asks how much the bus can carry. Compare measured throughput against peak bandwidth, the most the hardware can move in theory. If you’re far below peak, suspect latency; near peak, suspect bandwidth.

The Memory Latency Checker and STREAM supply baselines for your machine. Run one copy of your workload, then two, then one per core. Scaling points to latency; flattening early means the bus is saturated.

On multi-socket servers, NUMA (non-uniform memory access) makes remote memory slower to reach. The operating system usually places each page near the thread that first writes it, so have each thread initialize its own data. That’s first-touch placement.

Checking that your fix actually worked

Track LLC misses per message, LLC being the last-level cache before DRAM. Dividing by message count keeps the number fair across runs. Watch IPC (instructions per cycle) climb. A faster run alone can be noise. Numbers settle it.

Benchmark against a control: the unchanged build, same machine, same input. After the hash map rework, LLC misses per message fall and IPC climbs, so the review rests on numbers.

Ways to Make Memory Access Faster

Most of these fixes leave your algorithm alone and change how data sits in memory.

Access patterns that suit the cache

A std::list scatters nodes across the heap, so each hop can be a fresh cache miss, while a std::vector keeps elements side by side. A game engine programmer updating every particle each frame gets a walk the hardware can predict. Can’t swap containers?

Allocate nodes from a std::pmr arena so they stay close. In row-major order, the layout C and C++ multidimensional arrays use, the inner loop should move along a row, not down a column.

Finish each chunk’s passes before moving on, while the data is still hot.

Breaking big problems into cache-sized blocks

Split work into blocks small enough to stay cached while you reuse them. Recursion halves the problem until pieces fit, with no hard-coded size. Stencil algorithms, where outputs depend on neighbors, benefit from blocks that keep those neighbors resident.

Avoid machine-specific tuning: a size right on your laptop may be wrong on a server, so parameterize it and measure.

Blocked matrix transpose fixes a classic problem: a naive transpose strides across memory on one side, while tiling keeps both reads and writes inside cached blocks.

Storing fields apart keeps hot data lean

If your loop reads only x and y but each struct carries many other fields, every iteration drags the rest through the cache. Load only the fields the hot loop needs, and move cold ones elsewhere.

Measurements have shown a near 10x speedup, so benchmark your own code. An array of structures (AoS), such as a std::vector<Particle>, packs whole particles together, while a structure of arrays (SoA) packs each field together.

Contiguous x values let single instruction, multiple data (SIMD) units process several at once. A paper on data layout and SIMD abstraction layers notes that converting AoS to SoA can make co-accessed fields easier to load and process with SIMD.

A split drawing contrasts a cluttered conveyor belt with spilled items on the left against an organized bench with parallel processing trays on the right.
Figure 4 — A split drawing contrasts a cluttered conveyor belt with spilled items on the left against an organized bench with parallel processing trays on the right.

Ordering and padding fields for cache lines

The compiler inserts padding to align members, so a struct mixing a bool, a double and another bool wastes bytes. Order fields by size, largest first. Avoid #pragma pack on hot paths, since removing padding can leave members misaligned and slow access.

Alignment matters across threads too: when two threads write different variables that share a cache line, the line bounces between their cores. That cacheline ping-pong is false sharing.

Give each thread’s hot data its own line with alignas(std::hardware_destructive_interference_size) (C++17).

Fetching data before your code needs it

Hardware prefetchers catch regular patterns like a steady stride, so sequential loops rarely need help. For irregular access, such as tree walks or random lookups, software prefetch hints can load data early.

Prefetch too far ahead, or fetch data you never use, and you can pollute the cache, evicting lines you still need. Always benchmark.

Shrink data and cut dependent memory chains

Smaller types fit more elements per cache line: float over double where precision allows. Swap pointer chains for indices into a std::vector: a 32-bit index is half the size of a 64-bit pointer, and the storage stays contiguous.

Non-temporal stores bypass the cache for output you won’t reread soon. The translation lookaside buffer (TLB) caches address translations, so sprawling working sets miss often; huge pages cover more memory per entry.

Once memory bandwidth is saturated, adding threads doesn’t raise throughput, and the CopyCat paper makes a related point: past saturation, extra cycles just stall while waiting for memory.

Atomics cost too: the default std::memory_order_seq_cst is the strictest and usually the most expensive, so weaker orderings can help when they’re provably safe.

Basics of Managing Memory at Runtime

Before you can tell why a program is memory bound, you need to know where its memory comes from and who releases it.

Fixed memory versus memory requested at runtime

Some memory is static memory, fixed when the program loads. Other memory is dynamic memory, requested at runtime with new. A pointer in static memory has a fixed home, but the object it points to may be dynamic.

Local variables sit on the stack and are reclaimed when the function returns. Dynamic objects go on the heap and stay until you free them. The real difference is who releases it: the compiler for the stack, you for the heap.

How to allocate and free memory

Every new needs a matching delete. For one object, write auto* widget = new Widget{}; and later delete widget;. For an array, pair new[] with delete[], since mixing the two is undefined behavior.

After delete widget;, set the pointer to nullptr. Deleting a null pointer does nothing, so a later cleanup path can check it safely. It clears one variable, though, not every copy of the address.

Common mistakes with dynamic memory

  • Memory leaks. A game engine programmer who calls new[] for a particle buffer on every level load and never calls delete[] will see memory climb. Nothing frees it for you.
  • Lost or overwritten pointers. Assigning a new address before deleting the old one makes the first object unreachable, so it can never be freed.
  • Insufficient memory. When the heap can’t satisfy a request, new throws a std::bad_alloc exception. If nothing catches it, the program ends.
  • Double delete errors. Calling delete twice on one address is undefined behavior. Setting the pointer to nullptr after each delete blocks that second call through the same variable.

Being memory bound means your code spends its time waiting for data, so the fix starts with knowing where that wait comes from.

Latency and bandwidth set the limits, caches and virtual memory decide how often you pay them, and a profiler shows which one you’re really hitting.

Measure first, make layout changes that keep hot data together, and treat shared cache lines with care once threads enter the picture.

Feed the processor first, and the rest of your speed follows.

References

  1. Generic tiled layouts for high-performance multidimensional data structures — hal.science (2025)
  2. CopyCat: Harvesting the Frequency Tax of Bulk Memory Copy | Proceedings of the 18th ACM Workshop on Hot Topics in Storage and File Systems — dl.acm.org (2026)
  3. Data Layout and SIMD Abstraction Layers: Decoupling Interfaces from Implementations — doi.org (2018)
  4. drepper-wepskam — codelabs.ru

Questions

What is the difference between the `malloc()` and `calloc()` functions in C?

`malloc()` allocates a requested number of bytes and leaves the memory uninitialized. `calloc()` allocates space for a specified number of elements and initializes all allocated bytes to zero; both return a pointer to the allocated memory, or `NULL` if allocation fails.

What is the size of () in C?

There is no single size for `()` in C. If you mean the size of an empty struct, standard C does not allow empty struct definitions; the size of a particular object or type can be obtained with `sizeof`, such as `sizeof(int)`.

How to write "I love you" in C language?

You can print the phrase with `printf`: `#include <stdio.h>` followed by `int main(void) { printf("I love you\n"); return 0; }`.

Is C the hardest coding language?

C is not universally considered the hardest programming language. Its manual memory management, pointers, and low-level behavior can make it challenging, but difficulty depends on your experience and what you are trying to build.

Read next

  1. C++ generators: co_yield and std::generatorConcurrency · Miriam Castellanos · written for C++23
  2. std::mutex in C++: how to lock it, and which lock to useConcurrency · Miriam Castellanos · written for C++17
  3. Non-Uniform Memory Access Explained, With Tuning TipsConcurrency · Miriam Castellanos