Skip to content
CurriculumLesson 21 · Memory
Advanced~18 min

LRU & Optimal Page Replacement

LRU uses the past as a predictor of the future. Optimal uses the future directly. Comparing them tells you how much a real policy gives up.

In plain English

LRU guesses the future from the past. Optimal peeks at the future.

By the end you will be able to

  • Trace LRU replacement on a reference string.
  • Trace Optimal replacement on the same string.
  • Compare the fault counts.
  • Explain why Optimal is only a benchmark.
01

LRU

LRU evicts the page that has not been used for the longest time. On every hit, the page becomes the most recently used. On a fault, the least recently used page leaves. LRU approximates locality and is a stack algorithm, so it does not suffer Belady's anomaly. Exact LRU is expensive to implement; real systems approximate it with reference bits or clock hands.

lesson-21.osOS
on access(page):
    move page to most-recent position

on fault:
    victim = least-recent page
    evict(victim)
    insert(new_page)
02

Optimal replacement

Optimal evicts the page that will not be used for the longest time in the future. It produces the minimum possible number of faults for a given reference string and frame count. It cannot be implemented online because it needs future knowledge, but it is the benchmark against which real policies are measured.

03

Comparing the policies

Use the classic reference string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 with three frames. FIFO gives 15 faults. LRU gives 12, and Optimal gives 9. The exact counts depend on the string, but the pattern is typical: Optimal is best, LRU is close, and FIFO can be noticeably worse.

lesson-21.osOS
same reference string, 3 frames:
FIFO    -> 15 faults
LRU     -> 12 faults
Optimal ->  9 faults

Watch it happen

Step through the worked example. Play it, pause it, or move one step at a time.

policyreference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5

step-by-step

Step 1 of 12

Reference 1 · fault

Reference 1: miss. A free frame is available.

123412512345
frame 0
1
frame 1
—
frame 2
—
FAULTfaults so far: 1frames: 3

Key takeaways

  • LRU evicts the least recently used page.
  • LRU is a stack algorithm and avoids Belady's anomaly.
  • Optimal evicts the page used farthest in the future.
  • Optimal is a benchmark, not an online algorithm.
  • LRU is usually much better than FIFO and close to Optimal.

Common pitfalls

  • Updating recency on a fault but not on a hit.
  • Thinking Optimal can be implemented with future knowledge.
  • Assuming LRU always matches Optimal.

Kernel notes

  • Maintain recency order after every access.
  • Trace Optimal by scanning the future string.
  • Compare the final fault counts.

Quick check

0 / 2 answered

1. Which page does LRU evict?

2. Why can Optimal not be used in a real system?