How RAM and disk differ

· 2 min read

#how-it-works#hardware

RAM is the temporary workspace a computer uses while programs run, and disk is where files stay. The idea to keep: a program works on a copy of its data in RAM, and the computer moves data between the two.

The short version

The Linux kernel documentation calls physical memory volatile: what is in RAM does not survive without power, so most of it was read in from files. When a file is read, the kernel keeps its data in memory, in the page cache, so the next read skips the slow disk. Writes go to that cache first and reach the disk later. Apple's archived guide agrees on the cost: reading a page from disk is much slower than reading it from RAM.

How a file read and write moves between disk and RAM Three boxes in a row: Disk, RAM as page cache, and Program. Arrow 1 goes from Disk to RAM when a file is read. Arrow 2 goes from RAM to the program for later reads. A dashed arrow 3 goes from RAM back to Disk, because changed pages are written later. Disk kept without power RAM (page cache) temporary, limited Program reads and writes 1 read 2 use 3 changed pages are written later
Simplified: virtual memory and swap are left out.

Step by step

  1. A file sits on disk.
  2. A program reads it, and its data is copied into RAM, in the page cache.
  3. Later reads of the same data come from RAM, not from the disk.
  4. A change is made in RAM first, and the changed page is marked dirty.
  5. The kernel writes dirty pages to the storage device later, before it reuses the page.
  6. RAM has a fixed size. When it runs short, the system drops cached pages or writes them out, and reads them back from disk when needed.

Why it matters

A first read can be slower than the ones after it, and a change you just made may not be on disk yet. Think of RAM as the desk you work at and the disk as the cabinet: the desk is quick but small and gets cleared, the cabinet is slower and keeps things.

Sources