Skip to content

Cache Memory ​

Cache memory is memory used to reduce the bottleneck caused by the speed gap between a fast device and a slow device. Frequently used data is copied ahead of time to a fast place, and next time it is taken straight from there.

At a Glance ​

  • Analogy: it is like keeping the books you read often on your desk.
    • Going to the library (main memory) every time you need a book takes a long time.
    • If you keep a few frequently read books on your desk (the cache), you just reach out your hand.
    • But a desk is small (low capacity), and making it bigger is expensive (high cost).
  • Examples of where caches are used:
    • Easing the bottleneck between a CPU core and memory (RAM)
    • Web browser cache files: a web page file downloaded once is saved to disk, and next time it is read from disk instead of the network, easing the bottleneck between the web page and the hard disk

How a CPU Cache Works ​

When the CPU reads data from main memory, it stores frequently used data in cache memory. The next time that data is needed, the CPU checks cache memory before main memory and takes it from there, which makes things faster.

  • If the data the CPU requested is in the cache, it is a Cache Hit.
  • If it isn't in the cache and has to be fetched from a slower place (the next-level cache, or DRAM if it's not there either), it is a Cache Miss.

In exchange for the benefit of speed, it has the drawbacks of small capacity and high cost.

Memory Hierarchy and L1 · L2 · L3 Caches ​

text
          fast · small · expensive
               ▲
        ┌──────────────┐
        │  Registers   │  inside the CPU
        ├──────────────┤
        │  L1 cache    │  separate per core, tens of KB
        ├──────────────┤
        │  L2 cache    │  usually separate per core, hundreds of KB ~ a few MB
        ├──────────────┤
        │  L3 cache    │  shared by multiple cores, a few MB ~ tens of MB
        ├──────────────┤
        │ Main memory  │  RAM (DRAM), a few GB ~ tens of GB
        ├──────────────┤
        │  Secondary   │  SSD, HDD
        │   storage    │
        └──────────────┘
               ▼
          slow · large · cheap

The figure below tells the same story as a pyramid. The higher up (registers, cache), the faster and more expensive but smaller; the further down (RAM, flash, hard disk, tape), the slower but cheaper and larger. Also, the top three levels lose their contents when the power is turned off (power on), while the lower ones keep them even when the power is off (power off).

Memory hierarchy pyramid stacked in the order registers, cache, RAM, flash memory, hard disk, tape

Image source: Wikimedia Commons (Public domain)

A CPU usually contains 2~3 levels of cache memory, called the L1, L2, and L3 caches. They are divided by speed and size.

  • In general, the CPU checks starting from the L1 cache. It is the place the CPU can access fastest, and if the data isn't found there, it goes to L2, then L3, and finally RAM.
  • The higher the number, the larger the capacity but the slower it is.

Where Is the Cache? ​

In older computers, only L1 was inside the CPU, and L2 was sometimes between the CPU and RAM (outside the CPU) or on the motherboard, while L3 was attached to the motherboard. In modern CPUs, L1, L2, and L3 are all inside the CPU chip. They need to be on the same chip to exchange data quickly.

Caches in Multi-Core Processors ​

  • Each core has its own L1 cache.
  • In older dual-core processors (e.g. Intel Core 2 Duo), the two cores shared the L2 cache.
  • Modern processors usually keep L2 separate per core as well, and L3 is shared by all cores.

The L1 Cache Is Split into Instruction and Data Parts ​

The L1 cache is usually split in two.

NameWhat it holds
I-Cache (Instruction Cache)Instructions about to be executed
D-Cache (Data Cache)Data that instructions use in calculations

For example, if the L1 cache is 128KB, it is split into 64KB each, with instructions stored on one side and data on the other. The point is to let fetching instructions (the fetch cycle) and reading/writing data happen at the same time without getting in each other's way.

Why Caches Are Small ​

Cache memory uses SRAM. SRAM is much faster than the DRAM used for RAM, but it takes up much more chip area for the same capacity and is very expensive. That makes it hard to build large.

Disk Cache ​

A disk cache is a cache between main memory (RAM) and secondary storage (the hard disk). Content read from the slow disk is kept in RAM or in the disk's own buffer so that the next read doesn't have to go all the way to the disk. The principle is the same as a CPU cache; it is just one level lower in the hierarchy.

Why Caches Work So Well: Locality of Reference ​

Caches are highly effective even though they are small because programs don't use data at random; they show certain tendencies. This is called the principle of Locality of Reference.

Temporal Locality ​

Data that was referenced once is likely to be referenced again shortly.

  • Example: the condition variable i in a for or while loop is read again on every iteration.
  • Analogy: a book you just read is likely to be read again soon, so you keep it on your desk.

Spatial Locality ​

Data near the referenced data is likely to be used shortly.

  • Example: reading an array in order, like A[0], A[1], A[2]
  • Analogy: if you read page 3 of a book, you'll soon read pages 4 and 5 too, so you bring the whole book.

So when storing data in the cache, to make the most of spatial locality, it brings in not just the one piece of requested data but also the data at neighboring addresses as a single chunk, preparing for what will be used next. This chunk is called a Cache Line or block, and in modern CPUs it is usually 64 bytes.

Three Kinds of Cache Misses ​

1. Cold Miss ​

A miss caused by loading a memory address for the first time. It has never been fetched before, so it can't possibly be in the cache. It is also called a Compulsory Miss.

  • Analogy: for a book you've never seen, you have no choice but to go to the library.

2. Conflict Miss ​

A miss that happens when both data A and data B need to be stored in cache memory, but A and B are assigned to the same cache slot. Even if there are empty slots elsewhere, there is only one designated slot, so they keep pushing each other out. It happens a lot in the Direct Mapped cache described below.

  • Analogy: you've decided to put both your phone and your car key only in your right pocket, but the pocket fits just one. You moved the phone to your bag to make room for the key, so later when you look for the phone in your right pocket, it isn't there. Even if your left pocket is empty, the rule says you can't use it.

3. Capacity Miss ​

A miss caused by not having enough cache space overall. If the frequently used data is larger than the entire cache, something has to be pushed out no matter where things are placed.

  • A Conflict Miss is a slot assignment (address mapping) problem, while a Capacity Miss is an overall space problem.

But if you try to solve it by increasing the cache size, cache access gets slower and uses more power. So instead of size, efficiency is improved with structures like the ones below.

Cache Structures and How They Work ​

Direct Mapped Cache ​

The most basic structure. It is a many-to-one scheme in which multiple DRAM addresses map to one fixed slot in the cache.

Take as an example a situation with 32 memory addresses (00000 ~ 11111, 5 bits) and 8 cache slots (000 ~ 111, 3 bits).

text
 Memory address (5 bits)              Cache (8 slots)
 ┌─────┬───────┐                   ┌─────────┬──────┬────────┐
 │ Tag │ Index │                   │  Index  │ Tag  │  Data  │
 ├─────┼───────┤                   ├─────────┼──────┼────────┤
 │ 00  │  000  │ ──┐               │   000   │  ??  │  ...   │ ◀── four addresses fight over this one slot
 │ 01  │  000  │ ──┤               │   001   │      │        │
 │ 10  │  000  │ ──┼────────────▶  │   010   │      │        │
 │ 11  │  000  │ ──┘               │   ...   │      │        │
 └─────┴───────┘                   │   111   │      │        │
                                   └─────────┴──────┴────────┘
  • Addresses 00000, 01000, 10000, and 11000 all map to slot 000 of the cache.
  • Here, the last 3 bits (000) are the index field, which decides which slot, and the front part excluding the index (00, 01, 10, 11) is the tag field, which tells who is currently in that slot.
  • In this way, each cache slot consists of index field + tag field + data field.

Let's check in code how an address is split into an index and a tag.

python
# Direct mapped cache with 32 memory addresses (5 bits) and 8 cache slots (3 bits)
for addr in [0b00000, 0b01000, 0b10000, 0b11000, 0b01101]:
    index = addr % 8      # last 3 bits = which cache slot
    tag = addr // 8       # first 2 bits = a name tag telling who is in that slot
    print(f'Address {addr:05b} -> index {index:03b}, tag {tag:02b}')
text
Address 00000 -> index 000, tag 00
Address 01000 -> index 000, tag 01
Address 10000 -> index 000, tag 10
Address 11000 -> index 000, tag 11
Address 01101 -> index 101, tag 01

The advantage is that it is simple and fast. Just by looking at the index, there is exactly one slot to check. The disadvantage is that Conflict Misses happen often. As in the example above, if you have to alternate between data assigned to the same slot (000), they keep pushing each other out.

Below is a larger example that is closer to reality. 4096 main memory blocks are distributed across 64 cache lines, and blocks 64 slots apart, such as Block 0, 64, ..., all compete for the single Cache Line 0 slot. In the address breakdown at the bottom, the Index (bits 7~2) indicates which line, the Tag (bits 13~8) indicates who is in that line, and the Offset (bits 1~0) indicates which byte within the block.

Direct mapped cache where several main memory blocks map to one cache line, with the Tag, Index, Offset address breakdown

Image source: Wikimedia Commons (CC BY-SA 4.0)

Fully Associative Cache ​

A scheme that stores data anywhere in the cache where there is an empty slot.

  • Storing is very simple.
  • The problem is finding. Since there is no fixed rule, to check whether the desired data is present, you have to compare all blocks in the cache at once.
  • Comparing everything at once requires a special memory structure called CAM (Content Addressable Memory, memory searched by content), which is very expensive. So it is only used for special caches with few slots.

Set Associative Cache ​

A scheme that mixes direct mapping and full associativity.

  • The address decides which group (Set, row) the data goes into, and within that group it is stored in any empty slot (Way, column).
  • If a group has 2 slots, it is called a 2-way set associative cache; with 4, a 4-way set associative cache.

In the figure below, the left side is direct mapped and the right side is a 2-way set associative cache. With direct mapping, one memory location can go to only one cache slot, but with 2-way, it can go into either of the two slots (Way 0, Way 1) in the same group (Index).

Comparison of how memory addresses map to cache slots in a direct mapped cache and a 2-way set associative cache

Image source: Wikimedia Commons (CC BY-SA 3.0)

SchemeWhere data can goSlots to compare when searchingConflict MissHardware cost
Direct mappedFixed to exactly one slot1 slotManyCheapest
Set associativeAny slot within the assigned groupAs many as the slots in the groupMediumMedium
Fully associativeAny slot in the entire cacheAll slotsAlmost noneMost expensive

Compared with direct mapping, there are more slots to compare, so searching is a bit more complex, but conflicts drop sharply; compared with full associativity, there are a few conflicts, but it is much cheaper and faster to search. It is the middle ground. That is why most modern CPU caches use this scheme (e.g. 8-way, 16-way).

Comparing the Three Schemes Directly ​

Let's simulate, with three kinds of caches of the same size (8 slots), a situation that alternately reads two addresses, 00000 and 01000, which are assigned to the same slot (000).

python
def simulate(accesses, sets, ways):
    # sets: number of groups (rows), ways: number of slots per group
    cache = [[] for _ in range(sets)]   # list of tags in each group (oldest at the front)
    result = []
    for addr in accesses:
        index, tag = addr % sets, addr // sets
        row = cache[index]
        if tag in row:
            result.append('Hit')
            row.remove(tag)
        else:
            result.append('Miss')
            if len(row) == ways:
                row.pop(0)              # if the slots are full, evict the least recently used
        row.append(tag)
    return result

seq = [0b00000, 0b01000, 0b00000, 0b01000, 0b00000]
print('Direct mapped (8 sets x 1 slot):', simulate(seq, sets=8, ways=1))
print('2-way set associative (4 sets x 2 slots):', simulate(seq, sets=4, ways=2))
print('Fully associative (1 set x 8 slots):', simulate(seq, sets=1, ways=8))
text
Direct mapped (8 sets x 1 slot): ['Miss', 'Miss', 'Miss', 'Miss', 'Miss']
2-way set associative (4 sets x 2 slots): ['Miss', 'Miss', 'Hit', 'Hit', 'Hit']
Fully associative (1 set x 8 slots): ['Miss', 'Miss', 'Hit', 'Hit', 'Hit']
  • The first two Misses are Cold Misses, which happen in all three schemes.
  • In the direct mapped cache, even though the other 7 slots are empty, the two addresses keep pushing each other out of the same slot, so Conflict Misses keep happening afterward.
  • In the set associative cache, each group has 2 slots, so both addresses fit together and the accesses become Hits.

The rule for deciding what to evict from a full slot (in the code above, LRU, which evicts the least recently used) is the same idea covered in LRU and TTL.

Good to Know When Developing ​

  • Code that reads an array in order from the front is fast because spatial locality produces many cache hits.
  • For the same reason, the speed can differ a lot depending on whether you read a 2D array row by row or column by column. (In languages like C, elements of the same row sit next to each other in memory.)
  • For how a program's memory is laid out, see Memory Layout, and for the operating system's memory management, see Memory Management.

Summary ​

ConceptPlain-language summary
Cache memoryA desk where frequently used data is copied to a fast place
Cache hit / missIf it's on the desk, a hit; if you have to go to the library, a miss
L1 · L2 · L3The smaller the number, the faster and smaller. Today they are all inside the CPU chip
I-Cache / D-CacheL1 split into an instruction part and a data part
Temporal localityWhat you just used, you'll use again soon
Spatial localityYou'll soon use the neighbors of what you used, so data is fetched in chunks (cache lines)
Cold / Conflict / Capacity MissMisses caused by being the first time / overlapping slot assignments / not enough space
Direct mappedThe slot is fixed to one. Fast, but conflicts are frequent
Fully associativeUses any slot. No conflicts, but searching is expensive
Set associativeThe group is fixed, but free within it. The standard in modern CPUs

Reference: IT Donga - Cache Memory, Namuwiki - Cache Memory