Belajar
← All lessons

How RAM works

Store a word in memory

word.c

char word[] = "hello";  // say it lands at 0x1000// C adds a 0 byte after the last letter char *p = word;         // p holds 0x1000char c = p[1];          // same as *(p + 1)

Caches sit between the CPU and RAM so most reads skip the slow trip

CPU
L1 cache
L2 cache
RAM

read.c

char *a = malloc(1 << 20);  // 1 MB, in no cache yet char x = a[0];  // miss: L1, L2, then RAM                // RAM sends a[0] to a[63]char y = a[1];  // hit: same line, in L1 long sum = 0;for (int i = 0; i < n; i++)  // in order  sum += a[i];           // 1 miss per 64 readsfor (int i = 0; i < n; i++)  // random order  sum += a[rand() % n];  // almost every read misses

RAM forgets the moment the power goes

NotePowerOnOff
RAM
Disk note.txt

note.c

char note[16];strcpy(note, text);  // lives in RAM FILE *f = fopen("note.txt", "w");fwrite(note, 1, len, f);fclose(f);           // now it's on the disk // power off: every bit in RAM is gone f = fopen("note.txt", "r");fread(note, 1, len, f);  // back in RAM

Running out of RAM pushes pages to the disk

Browserneeds 3 GB · closed
Editorneeds 1 GB · closed
Gameneeds 4 GB · closed
RAM OS · one block is 512 MB
Swap on the disk

apps.c

// each app asks the OS for memorychar *tabs = malloc(3L << 30);  // 3 GB // RAM is full, so the OS moves pages// nobody used lately to swap on disk tabs[0] = 1;  // that page is on disk: page fault              // ~100 µs from the SSD, not ~100 ns free(tabs);   // the memory is free again

Topics

Next: How DNS works

Open lesson