Sub topic 5
Arrays versus linked structures
This chapter assumes you know what a cache line is and why sequential access is faster than scattered access. It also assumes you are comfortable with C pointers, structs, and Big-O notation. The goal is to decide when a contiguous array beats a pointer-based structure such as a linked list, and to know the cases where it does not.
The same Big-O, very different speed
Summing a linked list and summing an array are both O(n). Big-O counts operations. It does not count how long each operation waits for memory. The two loops below do the same arithmetic.
#include <stddef.h>
struct Node {
int value;
struct Node *next;
};
long sum_list(const struct Node *head) {
long s = 0;
for (const struct Node *n = head; n != NULL; n = n->next)
s += n->value;
return s;
}
long sum_array(const int *values, size_t n) {
long s = 0;
for (size_t i = 0; i < n; i++)
s += values[i];
return s;
}The array loop reads adjacent int values. With a 64-byte cache line and 4-byte integers, one line fill supplies 16 elements. Only the first access in each group of 16 can miss.
The list loop has a different problem. The address of the next node is stored inside the current node. The CPU cannot start loading node k+1 until node k has arrived. Each load depends on the previous one, so memory latency adds up instead of overlapping.
Dependent loads and pointer chasing
Pointer chasing is a sequence of loads where each address comes from the previous load. An out-of-order CPU can normally keep many memory requests in flight at once. A dependent chain removes that option, because only one request can be outstanding at a time.
The array loop is the opposite. Every address is base + i * 4, and the CPU can compute all of them in advance. Many loads overlap, and the hardware prefetcher (covered in a later chapter) can fetch lines before the loop asks for them.
What a node really costs
Look at struct Node above. On a typical 64-bit system it holds a 4-byte int and an 8-byte pointer. Alignment pads it to 16 bytes. Only 4 of those 16 bytes are data, so 75 percent of the memory traffic carries no payload.
A general-purpose allocator also adds a header, and rounds sizes up. A 16-byte request often consumes 32 bytes of heap. Then one 64-byte cache line holds two nodes, not 16 integers.
| Property | Array of `int` | Singly linked list of `int` |
|---|---|---|
| Bytes per element | 4 | 16 to 32 |
| Elements per 64-byte line | 16 | 2 to 4, if nodes are adjacent |
| Next address known in advance | Yes | No, needs a load |
| Prefetcher can help | Yes | Rarely |
| Insert in the middle | O(n) shift, given a position | O(1), given a node |
| Pointer to an element stays valid | Not after reallocation | Yes |
The table shows a trade. The list wins on insertion and stable addresses. The array wins on how much useful data each memory access brings in.
Seeing the effect
The diagram shows why a scattered list takes more memory round trips than an array.
Common errors
- Judging by operation counts. Comparing "O(1) insert" against "O(n) insert" ignores that finding the insertion point in a list is itself an O(n) pointer chase. For many sizes, shifting elements in an array with
memmoveis faster than walking to the right node. - Using a list for a queue or stack by habit. A growable array used as a stack, or a ring buffer used as a queue, gives the same operations with contiguous storage.
- Assuming nodes are adjacent. Adjacency depends on allocation history. Do not rely on it unless you control the allocator.
- Keeping pointers into a growing array. A
realloccan move the whole block. Store indices instead of pointers when elements must be referenced later. - Storing large payloads inline in both designs. A list of 200-byte structs spends most of each fetch on fields the traversal may not read. See the chapters on struct layout and hot and cold splitting.
Making linked structures less costly
When you need list-like behavior, you can keep much of the array's locality.
- Index links in an array (a pool). Store nodes in one array and replace pointers with 32-bit indices. Nodes stay in one block, links shrink from 8 bytes to 4, and freed slots can be reused through a free list.
- Unrolled lists. Each node holds a small array of elements, for example 14 integers that fill one cache line along with a count and a link. Traversal makes one dependent load per 14 elements instead of one per element.
- Arena allocation. Allocate nodes from one large block in the order you will traverse them. The pointers remain, but adjacent nodes are adjacent in memory.
The following program shows the index-link version of a list. It builds a list in a pool and sums it.
#include <stdio.h>
#include <stdint.h>
#define CAP 8
#define NIL UINT32_MAX
struct PoolNode {
int value;
uint32_t next; /* index into the pool, or NIL */
};
int main(void) {
struct PoolNode pool[CAP];
uint32_t head = NIL;
/* Push front: each new node takes the next free slot. */
for (uint32_t i = 0; i < CAP; i++) {
pool[i].value = (int)(i + 1);
pool[i].next = head;
head = i;
}
long sum = 0;
for (uint32_t k = head; k != NIL; k = pool[k].next)
sum += pool[k].value;
printf("%ld\n", sum); /* prints 36 */
return 0;
}Each node is 8 bytes, so a cache line holds eight of them. The traversal still depends on next, but the dependent loads usually hit lines already in cache.
Decision criteria
Choose a contiguous array (or a vector type) when:
- you traverse the whole collection often,
- elements are small,
- insertions and removals mostly happen at the end, or order does not matter (you can remove by swapping with the last element),
- you need fast random access by position.
Consider a linked structure when:
- elements are large and expensive to move,
- other code holds references to elements that must stay valid,
- you splice whole sequences together in O(1),
- you insert and remove at known nodes far more often than you traverse.
When unsure, write the array version first and measure. The chapter on measuring cache behavior covers how to do that without misleading yourself.
Exercise
A program stores 1,000,000 int values in a singly linked list with 16-byte nodes, and it sums them repeatedly. A colleague proposes switching to a plain int array and expects a large speedup, but says "both are O(n), so it can't matter." Give two concrete reasons the array should be faster, and name one situation where the list would still be the right choice.
Show answer
First, the array packs 16 values into each 64-byte line, while the list fits at most 4 nodes per line even when nodes are adjacent, so the list moves about four times as many bytes through the cache. Second, list traversal is a chain of dependent loads, so memory latencies add up and the prefetcher cannot run ahead, while array addresses are computable in advance and loads overlap. The list is still right when other code holds long-lived references to elements, or when the program mostly splices or removes at known nodes and rarely traverses.