Memory and cache

Close is fast · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

RAM

A computer has 3 places to store data. The disk keeps everything long term: the system, programs, files; it's big, terabytes, but slow. RAM holds what programs are using right now; it's smaller, gigabytes, and much faster. The cache sits inside the processor and holds what's used very often; it's tiny, megabytes, and super fast. It's like a kitchen: the pantry, the counter and your hand.

RAM and cache lose everything when the power goes out: they're called volatile. The disk keeps data even when the computer is off. That's why RAM can't replace the disk: besides losing data, it costs tens of times more per gigabyte. When a program starts, its data is read from disk into RAM, and the cache keeps bringing from RAM what the processor uses often.

CPU cache miss

When the processor asks for data and it's in the cache, it's a hit: it gets it in nanoseconds. When it isn't, it's a cache miss: it has to go get it from RAM, which takes much longer. The percentage of requests served from the cache is called the hit rate, and it's the main measure of how well the cache is used. Fewer misses, faster program.

Arrays make much better use of the cache than linked lists, for 4 reasons. They're more compact, so more useful data fits in the cache. They're adjacent, so each line brought in holds data that will be used. They're walked in a predictable order, so prefetching hits. And an element's neighbors are the next ones read. That's why, with the same complexity, walking an array is usually quite a bit faster.

Spatial locality

The cache uses 4 tricks to hit more often. It brings data in lines, blocks of about 64 bytes, not 1 byte at a time. It reads ahead: if it sees you reading in order, it brings what comes next before you ask. It uses spatial locality: if you read some data, you'll probably read its neighbors. And temporal locality: if you used some data, you'll probably use it again soon, so it keeps it for a while.

Fragmentation

When a program asks for and frees memory many times, free memory ends up split into small gaps: that's fragmentation. Arrays take one adjacent block and fragment little. Linked lists scatter nodes everywhere and fragment more. Even so, the linked list has its place: when there's a huge amount of data, the size changes a lot and can't be guessed, a stack on a linked list avoids having to grow and copy a huge array.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Close is fast