Sub topic 9
Splitting Hot and Cold Data
This chapter assumes you know the cache-line model from earlier chapters: memory moves in 64-byte lines, and a loop is fast when most bytes in each loaded line get used. It also assumes you are comfortable with C structs and the array-of-structs versus struct-of-arrays distinction.
What hot and cold mean
Hot data is the set of fields that a performance-critical loop reads or writes often. Cold data is everything else: fields used rarely, only on error paths, or only when displaying one record to a human.
Most record types mix the two. A user record might hold an ID, a score, and an active flag, which a ranking loop reads millions of times. The same record also holds a name, an email address, and a biography, which are touched only when someone opens a profile page.
If hot and cold fields sit in one struct, every cache line the loop loads is mostly cold bytes. The loop pays memory bandwidth and cache capacity for data it never reads. Splitting means moving the fields apart so the hot ones are packed together.
The cost of mixing
Consider this record. The hot fields take 7 bytes. The cold fields take 240.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N (1u << 19)
struct UserMixed {
uint32_t id;
uint16_t score;
uint8_t active;
char name[48];
char email[64];
char bio[128];
};
struct UserHot {
uint32_t id;
uint16_t score;
uint8_t active;
};
struct UserCold {
char name[48];
char email[64];
char bio[128];
};
static uint64_t sum_mixed(const struct UserMixed *u, size_t n) {
uint64_t s = 0;
for (size_t i = 0; i < n; i++)
if (u[i].active)
s += u[i].score;
return s;
}
static uint64_t sum_hot(const struct UserHot *u, size_t n) {
uint64_t s = 0;
for (size_t i = 0; i < n; i++)
if (u[i].active)
s += u[i].score;
return s;
}
int main(void) {
struct UserMixed *mixed = calloc(N, sizeof *mixed);
struct UserHot *hot = calloc(N, sizeof *hot);
struct UserCold *cold = calloc(N, sizeof *cold);
if (!mixed || !hot || !cold) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (size_t i = 0; i < N; i++) {
uint16_t score = (uint16_t)(i % 1000);
uint8_t active = (i % 3) != 0;
mixed[i].id = (uint32_t)i;
mixed[i].score = score;
mixed[i].active = active;
hot[i].id = (uint32_t)i;
hot[i].score = score;
hot[i].active = active;
snprintf(mixed[i].name, sizeof mixed[i].name, "user%zu", i);
snprintf(cold[i].name, sizeof cold[i].name, "user%zu", i);
}
printf("sizeof mixed=%zu hot=%zu cold=%zu\n",
sizeof(struct UserMixed), sizeof(struct UserHot),
sizeof(struct UserCold));
for (int run = 0; run < 3; run++) {
clock_t t0 = clock();
uint64_t a = sum_mixed(mixed, N);
clock_t t1 = clock();
uint64_t b = sum_hot(hot, N);
clock_t t2 = clock();
printf("mixed %.2f ms hot %.2f ms sums %llu %llu\n",
1000.0 * (double)(t1 - t0) / CLOCKS_PER_SEC,
1000.0 * (double)(t2 - t1) / CLOCKS_PER_SEC,
(unsigned long long)a, (unsigned long long)b);
}
/* Cold data is still reachable by the same index. */
printf("user 12345 is %s\n", cold[12345].name);
free(mixed);
free(hot);
free(cold);
return 0;
}On common x86-64 ABIs the sizes print as 248, 8, and 240. In the mixed layout, each element spans about four cache lines, and the loop reads only one byte pair and one flag from each. Roughly one line is loaded per element. In the hot layout, eight elements share one 64-byte line, so one load serves eight iterations.
Timings depend on your machine. Expect the hot version to be several times faster once the array no longer fits in cache. The program's sums should match, and you should confirm that they do.
Three ways to split
The shared index in the example is one option. The common designs differ in how they connect a hot record to its cold data.
| Design | How cold data is found | Strength | Weakness |
|---|---|---|---|
| Parallel arrays | Same index `i` in a second array | No extra storage, simple | Both arrays must be reordered together |
| Pointer in hot struct | `hot[i].cold` points to a heap block | Cold data can be allocated lazily | Costs 8 bytes per hot record and one extra miss per access |
| Index or handle in hot struct | `hot[i].cold_id` indexes a cold pool | Survives reallocation, 4 bytes | Needs a pool and a lookup step |
Parallel arrays suit data that is built once and rarely reordered. A pointer or handle suits data where only some records have cold parts, such as an optional attachment or a rarely-set error description.
Deciding what is cold
Classify by measured access frequency in the loops you care about, not by how important a field feels. The diagram shows the decision for one field.
A field that a hot loop reads but never alongside the other hot fields belongs in its own group. That is the struct-of-arrays case from the previous chapter. Hot and cold splitting is the coarser step: first separate what the hot path needs from what it does not, then decide whether the hot part should itself be an array of structs or a struct of arrays.
Sizing the hot struct
A split pays off in proportion to how many hot records fit in a line. Check three things after you split.
- Print
sizeoffor the hot struct and confirm there is no surprising padding. Apply the field-ordering rules from the alignment chapter. - Prefer a hot size that divides 64 evenly (8, 16, 32). Otherwise some records straddle two lines and cost two loads.
- Align the array start to 64 bytes if you need that guarantee.
malloctypically gives 16-byte alignment, so usealigned_alloc(64, size)oralignas(64)where it matters.
Failure modes
Splitting is not free. These are the usual ways it backfires.
- Wrong classification. If a hot loop reads a "cold" field on every iteration, you now take two cache misses per record instead of one. Check the hot loops before you move a field.
- Access by whole record. Code that always needs the full record, such as serialization or copying, gets slower because it must visit two arrays.
- Synchronization bugs. With parallel arrays, sorting, swapping, or deleting in one array and not the other silently corrupts the pairing. Wrap these operations in a function that moves both.
- Pointer chasing. A pointer from hot to cold adds 8 bytes to each hot record and sends rare accesses to unpredictable addresses. That is acceptable only if those accesses really are rare.
- Premature splitting. If the whole data set fits in L1 or L2 cache, the difference is small. Split when profiling shows cache misses on this loop.
Hot and cold in code, not just data
The same idea applies to instructions. Error handling and logging code placed in the middle of a hot function wastes instruction-cache space. Moving rare branches into separate functions, and marking them __attribute__((cold)) in GCC and Clang, lets the compiler place them away from the hot path. This is a smaller effect than data splitting but follows the same principle.
Exercise
A struct has fields uint64_t key (read in every lookup), uint64_t value (read only after a key match), char description[96] (read when printing a report), and uint32_t flags (read in every lookup). You scan an array of 10 million of these records for a key. Which fields would you place in the hot struct, and what would its size be with sensible field ordering?
Show answer
Put key and flags in the hot struct. The scan reads them on every record. value is read only on a match, so it can stay cold, and description is clearly cold. The hot struct is uint64_t key; uint32_t flags;, which is 12 bytes of data padded to 16, so four hot records fit in each 64-byte line. If you also keep value in the hot struct, it grows to 24 bytes, and fewer records fit per line.