Learning Notes are short posts about the bit I got stuck on, the example I tried, and what made it click.

I’m learning more about garbage collection, starting with Go’s Green Tea collector. I got stuck on prefetching: how does the CPU know what to fetch if it hasn’t read the data yet?

Say we have a struct B with a pointer B.Next to another struct C. Reading B.Next gives us C’s address, not C’s contents. So we can ask the CPU to start fetching C while it scans B’s other fields.

Watch the fetch overlap the scan

CPU and memory activity with and without prefetchingWithout prefetch, the CPU scans B for one tick, then waits for C for two ticks. With prefetch, the two-tick fetch starts during the scan, so the CPU can read C in the third tick.Tick 1Tick 2Tick 3Without prefetchCPUMemoryScan BWaitFetch CIdleWith prefetchCPUMemoryScan BWaitFetch CIdleRead C

Both runs start just after reading C’s address from B.

  1. Both runs scan B. With prefetch, memory starts fetching C during that same tick.
  2. Without prefetch, C’s fetch is just starting. With prefetch, it’s already halfway done.
  3. The prefetch run can read C while the other run is still waiting.

The bit that made it click for me: the fetch still takes two ticks. We just spent one of those ticks doing work on B instead of waiting for C.

If we ask too late, we still have to wait. If we ask too early, C might get kicked out of the cache before we read it. What we want is enough time to do other work while C is on its way.

That’s it!