Skip to content

Cache Line

Spicy — senior dev territoryBackend

ELI5 - The Vibe Check

Your CPU never fetches just the one byte you asked for, it grabs a whole chunk around it, usually 64 bytes, called a cache line, on the theory that you'll probably want the neighbors soon too. This is great when it's true, and it's the hidden reason two totally unrelated variables sitting next to each other in memory can secretly slow each other down.

Real Talk

A cache line is the fixed-size block of memory, typically 64 bytes on modern x86 and ARM CPUs, that is the smallest unit transferred between main memory and CPU caches. Because an entire line is loaded and invalidated as a unit, the physical layout of data in memory has a direct, sometimes surprising, effect on cache efficiency and multi-core performance.

Show Me The Code

struct Counter {
  std::atomic<int> a; // shares a cache line with b
  std::atomic<int> b;
};
// Pad so hot fields land on separate cache lines:
struct Counter {
  alignas(64) std::atomic<int> a;
  alignas(64) std::atomic<int> b;
};

When You'll Hear This

"Those two counters share a cache line, that's the false sharing you're seeing." / "Pad the struct so hot fields land on separate cache lines."

Made with passive-aggressive love by manoga.digital. Powered by Claude.