TechBuzzPro

CPU cache explained: what it is and how it works

· 6 min read · Windows & PC

In this article
  1. Background: why a cache is needed
  2. How a CPU cache works
  3. Cache hierarchy: L1, L2, and L3
  4. Cache lines, associativity, and replacement policies
  5. Cache coherence and multi‑core processors
  6. Common performance problems related to cache
  7. Choosing the right cache‑aware strategies
  8. Comparisons with other memory technologies
  9. Safety considerations when tweaking cache‑related settings
  10. Frequently Asked Questions

A CPU cache is a small, fast memory located on or very close to the processor that stores copies of frequently accessed data to speed up execution.

Background: why a cache is needed

Modern processors can perform billions of operations per second, but the main memory (DRAM) that holds program data is orders of magnitude slower. A typical DDR4 DIMM has a latency of 70–100 nanoseconds, while a single arithmetic operation may complete in less than 1 nanosecond. Without a mechanism to bridge this speed gap, the CPU would spend most of its cycles waiting for data, dramatically reducing overall performance. The cache hierarchy was introduced to keep the most useful data as close to the execution units as possible.

How a CPU cache works

When the processor needs a byte of data, it first checks the smallest and fastest cache level (L1). If the data is present—a condition called a cache hit—the CPU reads it in a few clock cycles. If the data is absent—a cache miss—the request is forwarded to the next cache level (L2), and eventually to main memory if none of the caches contain the data. Each level is larger and slower than the one before it, forming a pyramid of storage.

The basic steps for a read operation are:

  1. Lookup the address in the L1 cache tags.
  2. If the tag matches and the line is valid, return the data (hit).
  3. If not, request the line from L2 and repeat the check.
  4. On a miss at the last cache level, fetch the line from DRAM, store it in all cache levels according to the replacement policy, then deliver it to the CPU.

Write operations follow similar rules but must also keep the copies coherent. Most CPUs use a write‑back policy: the modified line is written to the cache first and only written back to memory when it is evicted.

Cache hierarchy: L1, L2, and L3

Typical desktop and laptop CPUs have three levels:

  • L1 cache – split into instruction (I‑cache) and data (D‑cache) sub‑caches, each 32 KB to 64 KB per core. Latency is usually 3–4 cycles.
  • L2 cache – unified for instructions and data, sized 256 KB to 1 MB per core. Latency is about 10–12 cycles.
  • L3 cache – shared among all cores on the die, ranging from 2 MB to 32 MB. Latency is roughly 30–40 cycles.

Because the L1 cache is private to each core, two threads running on different cores can each have a copy of the same memory line. The shared L3 cache reduces duplication and helps maintain coherence across cores.

Cache lines, associativity, and replacement policies

Data is transferred between memory and cache in fixed‑size blocks called cache lines. Most modern CPUs use a 64‑byte line size. When a program accesses any byte within a line, the whole line is brought into the cache.

Caches are not simple direct‑mapped tables; they are usually set‑associative. A set‑associative cache with an associativity of 8 means each address can be placed in any of eight slots within a particular set. This reduces conflict misses compared with a purely direct‑mapped design.

When a set is full and a new line must be inserted, the cache uses a replacement policy, most commonly Least Recently Used (LRU) or a pseudo‑LRU approximation. The policy decides which existing line to evict.

Cache coherence and multi‑core processors

In a multi‑core system, each core may have its own L1 and L2 caches, while sharing an L3. To keep copies of the same memory location consistent, CPUs implement a coherence protocol. The most widespread is MESI (Modified, Exclusive, Shared, Invalid). The protocol tracks the state of each cache line and issues bus transactions to invalidate or update other cores when a line is written.

For example, if Core 0 writes to a line that Core 1 also holds, the MESI protocol marks Core 1’s copy as Invalid and sends the updated data to Core 0’s cache. Subsequent reads by Core 1 will cause a miss and fetch the new value, preserving correctness.

Even though caches dramatically improve speed, certain coding patterns can defeat them:

  • Cache thrashing: Accessing more distinct lines than the cache can hold in a tight loop forces continuous evictions, leading to a high miss rate.
  • False sharing: Two threads write to different variables that reside on the same cache line. The line bounces between cores, causing unnecessary coherence traffic.
  • Unaligned accesses: Reading data that straddles a cache line boundary may require two line fetches, effectively doubling the cost.

Profiling tools such as Intel VTune or Linux perf can report cache‑miss rates, helping developers locate these bottlenecks.

Choosing the right cache‑aware strategies

When writing performance‑critical code, consider these guidelines:

  1. Structure data so that elements accessed together are stored contiguously (e.g., arrays of structs vs. struct of arrays).
  2. Prefer loop orders that iterate over the innermost dimension matching the memory layout, ensuring sequential access.
  3. Pad structures to avoid false sharing; adding a 64‑byte alignment attribute can keep each thread’s data on a separate line.
  4. Use prefetch instructions (e.g., _mm_prefetch) only after measuring a genuine benefit, as premature prefetching can waste bandwidth.

These techniques do not change the hardware cache, but they make the existing hierarchy work more efficiently.

Comparisons with other memory technologies

It is a common misconception that a cache is simply “fast RAM.” While both store data, their purposes differ:

  • DRAM (main memory) is large (gigabytes), volatile, and accessed over a memory bus that introduces significant latency.
  • CPU cache is tiny (kilobytes to megabytes), built from SRAM cells that are faster but consume more silicon area per bit.
  • Non‑volatile memory (NVMe, SSD) offers persistence but has latency measured in microseconds, far slower than even L3 cache.

Emerging technologies like Intel’s Optane DC Persistent Memory blur the line between RAM and storage, but they still cannot match the nanosecond‑scale latency of on‑die caches.

Most users never need to modify cache parameters; they are hard‑wired into the processor. Some BIOS/UEFI firmware allow disabling the L3 cache for debugging, but doing so can cause severe performance degradation and may expose the system to instability if software assumes the cache hierarchy exists. Always revert such changes before returning to production use.

Frequently Asked Questions

What is the typical size of an L1 cache?

Modern desktop and laptop CPUs usually provide 32 KB to 64 KB of instruction cache and the same amount of data cache per core.

How does a cache miss affect program speed?

A miss forces the CPU to fetch data from a slower level, adding roughly 10–100 cycles for an L2 miss and 200–400 cycles for an L3 miss, depending on the architecture.

Can software directly control the CPU cache?

Only indirectly. Developers can influence cache behavior through data layout, loop ordering, and optional prefetch intrinsics, but they cannot allocate or free cache lines explicitly.

What is ‘cache line’ and why is it 64 bytes?

A cache line is the smallest unit transferred between memory and cache. 64 bytes became a de‑facto standard because it balances transfer efficiency with reasonable granularity for most workloads.

Why does multithreaded code sometimes run slower on more cores?

When threads contend for the same cache lines (false sharing) or generate excessive coherence traffic, the overhead can outweigh the benefits of parallel execution.

Is disabling the L3 cache ever useful?

Disabling L3 is generally only done for low‑level hardware debugging; it dramatically reduces performance and can cause timing‑sensitive software to misbehave.