CPU cache
Кэш процессора
A small amount of fast memory inside the processor keeps copies of data and instructions so that the CPU can often use them without waiting for main memory.
Also known as: L1 кэш, cache line
Why the CPU needs a cache
Fetching data from main memory (RAM) takes much longer than fetching it from a CPU cache. The hardware keeps blocks of memory close to the cores so they can reuse those blocks without going back to RAM. Unlike an application cache, a CPU cache does not require the program to decide what to insert or look up: ordinary loads and instruction fetches use it automatically for cacheable memory.
Cache lines and levels
The unit of storage is a cache line, a block of consecutive bytes. Many processors use 64-byte lines, but the size is hardware-dependent. On a machine with 64-byte lines, a single line can hold 16 consecutive 4-byte integers if the first integer starts at a line boundary. Reading one integer can therefore bring its neighbors into the cache as well.
A hit means the requested line is present at the level being checked. A miss means that level cannot supply it. L1 is typically the smallest and fastest level, with separate instruction and data caches on each core. L2 is usually larger and slower, and an L3 cache, where present, is often shared by several cores. An L1 miss does not necessarily go to RAM; another cache level may have the line. When a line needs to be brought in and all the slots it can occupy are full, the hardware picks a line to evict.
Example: same number of additions, different memory access
In a two-dimensional C array, elements within a row are stored next to each other. To sum a large matrix row by row, vary j in the inner loop of a[i][j]. Once a line arrives, the next few reads can use it. If you vary i in the inner loop instead, consecutive reads jump between rows. By the time you return for an element in the next column, its line may have been evicted. Both loops do the same number of additions, yet the row-by-row traversal often finishes sooner.
Performance work and interviews
Cache behavior matters in numerical loops, data structure traversal, and multithreaded code. One common surprise is false sharing: two cores repeatedly write to different variables that happen to occupy the same line. Each core needs permission to write the whole line, so the line can bounce between cores even though the threads do not share a variable. That is a performance problem, not by itself a data race.
An interviewer might ask why a linear scan of an array often beats traversal of a linked list with scattered nodes, even though both are O(n). Explain spatial locality: touching nearby addresses makes use of bytes already fetched with a line. Contrast it with temporal locality: touching the same data again before its line is evicted. Big O does not capture these effects; use a benchmark with representative data to check whether a layout change actually helps.