Skip to content

Page Replacement Algorithms (FIFO · OPT · LRU · LFU) ​

A page replacement algorithm is the rule that decides which of the already-loaded pages to evict when memory is full and a new page needs to be loaded. The better the choice, the fewer page faults occur and the faster the program runs.

At a Glance ​

  • Analogy: you can only keep 3 books open on your desk (memory), but you need to read a new one. One book has to go back to the stacks (disk). Whether you send back "the book taken out first," "the book you'll need furthest in the future," "the book you haven't looked at for the longest time," or "the book you've looked at the least" is exactly the difference between the algorithms.
  • The page evicted at this point is called the victim page.
  • Paging, virtual memory, and the steps of page replacement are covered in Memory Management.

Why Page Replacement Is Needed ​

Virtual memory uses Demand Paging: only the pages needed right now are loaded into memory, and the unused parts stay on disk.

But even loading only the needed pages, memory eventually fills up. On top of that, a page that has been loaded may keep occupying space even after it is no longer needed. So when memory is full, an unused page must be evicted (out) and the page needed now brought in (in) in its place.

If possible, it is better to evict an unmodified page. A modified page has to have its changed contents written back to disk when evicted, which takes more time. (The modify bit used to check this is explained in Memory Management.)

Page Reference String ​

The CPU requests memory by logical address, but memory is loaded page by page. So if addresses in the same page are requested one after another, only the first one matters; for the rest, the page is already loaded, so a page fault cannot happen.

That is why, when comparing algorithms, instead of addresses we write only the page numbers in order, collapsing consecutive repeats of the same number into one. This is called the page reference string.

text
Requested address (page size 100) : 0100 0432 0101 0612 0102 0103 0104 0611
Page number                       :   1    4    1    6    1    1    1    6
Reference string (repeats merged) :   1    4    1    6    1              6

Every example in this article is compared using the reference string below and 3 frames. It is a common example in operating systems textbooks.

text
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1

Simulator Code ​

The tables below were not drawn by hand; they are the results of actually running this Python simulator.

python
def simulate(refs, n_frames, policy):
    frames = []        # pages currently loaded in memory
    loaded_at = {}     # when each page was loaded into memory (for FIFO)
    last_used = {}     # when each page was last used (for LRU)
    use_count = {}     # how many times each page has been used so far (for LFU)
    faults = 0
    log = []

    for t, page in enumerate(refs):
        victim = None
        if page in frames:
            result = "Hit"
        else:
            result = "Fault"
            faults += 1
            if len(frames) == n_frames:  # if there is no free slot, evict one
                if policy == "FIFO":     # the page that came in first
                    victim = min(frames, key=lambda p: loaded_at[p])
                elif policy == "OPT":    # the page that will be used furthest in the future
                    def next_use(p):
                        rest = refs[t + 1:]
                        return rest.index(p) if p in rest else float("inf")
                    victim = max(frames, key=next_use)
                elif policy == "LRU":    # the page used longest ago
                    victim = min(frames, key=lambda p: last_used[p])
                elif policy == "LFU":    # the least used page (if tied, the one that came in first)
                    victim = min(frames, key=lambda p: (use_count[p], loaded_at[p]))
                elif policy == "MFU":    # the most used page (if tied, the one that came in first)
                    victim = min(frames, key=lambda p: (-use_count[p], loaded_at[p]))
                frames[frames.index(victim)] = page
                del use_count[victim]
            else:
                frames.append(page)
            loaded_at[page] = t
            use_count[page] = 0
        last_used[page] = t
        use_count[page] += 1
        log.append((t + 1, page, list(frames), result, victim))
    return faults, log

refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1]

if __name__ == "__main__":
    for policy in ["FIFO", "OPT", "LRU", "LFU", "MFU"]:
        faults, log = simulate(refs, 3, policy)
        print(f"{policy}: {faults} page faults")
text
FIFO: 15 page faults
OPT: 9 page faults
LRU: 12 page faults
LFU: 13 page faults
MFU: 15 page faults

The "Frames" column in the tables lists the pages in the 3 frames in slot order, and - means an empty slot. For the first three requests, memory is empty, so every algorithm has a fault no matter what.

1. FIFO (First In First Out) ​

The page loaded into memory first is evicted first. It works like a queue.

  • It is the simplest, so it is easy to implement.
  • It suits initialization code well. Initialization code is needed only once when the process first runs and is not used after that. Since it is definitely needed at the start, it is loaded first, and FIFO evicts what was loaded first, so it gets cleaned up naturally once initialization is over.
  • However, "came first" has nothing to do with "won't be used in the future." A page that was loaded early but is used continuously (e.g. a frequently called function) also gets evicted when its turn comes, causing another fault right away.
StepRequestFramesResultEvicted page
177 - -Fault
207 0 -Fault
317 0 1Fault
422 0 1Fault7
502 0 1Hit
632 3 1Fault0
702 3 0Fault1
844 3 0Fault2
924 2 0Fault3
1034 2 3Fault0
1100 2 3Fault4
1230 2 3Hit
1320 2 3Hit
1410 1 3Fault2
1520 1 2Fault3
1600 1 2Hit
1710 1 2Hit
1877 1 2Fault0
1907 0 2Fault1
2017 0 1Fault2

15 page faults. You can see waste like this several times: at step 6, page 0, which was just used at step 5, is evicted, and then it has to be loaded again at the very next step 7.

Here is the same process as a figure. Blue cells are newly loaded pages, and steps that were hits with no change are omitted from the figure.

FIFO page replacement: 15 page faults on the same reference string

Image source: gyoogle tech interview notes, Page Replacement Algorithm

Belady's Anomaly ​

Common sense says that adding frames should reduce page faults. But with FIFO, there are cases where adding frames actually increases faults.

With the simulator above saved as paging.py, frames 3 and 4 were compared on a different reference string.

python
from paging import simulate
refs = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for n in (3, 4):
    print(f"FIFO, {n} frames: {simulate(refs, n, 'FIFO')[0]} page faults")
text
FIFO, 3 frames: 9 page faults
FIFO, 4 frames: 10 page faults

This does not happen with OPT or LRU.

2. OPT (Optimal Replacement) ​

The page that will not be used for the longest time in the future is evicted. If there is a page that will never be used again, it is the first choice.

  • In theory, it is the algorithm with the fewest page faults. It can cut faults dramatically compared with FIFO.
  • In practice, however, it cannot be used, because the operating system cannot know in advance which pages a program will request.
  • So OPT is used as a benchmark for measuring how good other algorithms are, in comparisons like "how close does LRU get to OPT?"
StepRequestFramesResultEvicted page
177 - -Fault
207 0 -Fault
317 0 1Fault
422 0 1Fault7
502 0 1Hit
632 0 3Fault1
702 0 3Hit
842 4 3Fault0
922 4 3Hit
1032 4 3Hit
1102 0 3Fault4
1232 0 3Hit
1322 0 3Hit
1412 0 1Fault3
1522 0 1Hit
1602 0 1Hit
1712 0 1Hit
1877 0 1Fault2
1907 0 1Hit
2017 0 1Hit

9 page faults. With the same reference string and number of frames, you cannot do better than this. For example, at step 6 when page 3 comes in, of 2, 0, and 1, the one used furthest in the future, page 1 (step 14), is evicted.

In the figure, there are noticeably fewer fault steps than with FIFO.

OPT page replacement: 9 page faults on the same reference string

Image source: gyoogle tech interview notes, Page Replacement Algorithm

3. LRU (Least Recently Used) ​

The page that has gone unused for the longest time is evicted. It comes from the idea that "what hasn't been used recently won't be used in the future either."

  • OPT looks at the future, but LRU decides by looking at the past, so it can actually be used.
  • Real programs strongly tend to reuse recently used data soon (temporal locality), so a page not used recently is likely not to be used in the future either.
  • It may cause more faults than OPT, but it is one of the best methods among algorithms that can actually be used.
StepRequestFramesResultEvicted page
177 - -Fault
207 0 -Fault
317 0 1Fault
422 0 1Fault7
502 0 1Hit
632 0 3Fault1
702 0 3Hit
844 0 3Fault2
924 0 2Fault3
1034 3 2Fault0
1100 3 2Fault4
1230 3 2Hit
1320 3 2Hit
1411 3 2Fault0
1521 3 2Hit
1601 0 2Fault3
1711 0 2Hit
1871 0 7Fault2
1901 0 7Hit
2011 0 7Hit

12 page faults. That is 3 fewer than FIFO (15) and fairly close to the optimum (9).

Here it is as a figure. Each cell in the figure corresponds one-to-one with a fault step in the table above.

LRU page replacement: 12 page faults on the same reference string

Image source: gyoogle tech interview notes, Page Replacement Algorithm

LRU is used heavily not only in page replacement but also in caches. How LRU is implemented in a cache like Redis is covered in LRU and TTL.

4. LFU (Least Frequently Used) ​

The page used the fewest times so far is evicted. Pages used often are considered important and kept. When use counts are tied, the page that came in first was evicted. (This simulator resets the count to 0 when a page leaves memory.)

StepRequestFramesResultEvicted page
177 - -Fault
207 0 -Fault
317 0 1Fault
422 0 1Fault7
502 0 1Hit
632 0 3Fault1
702 0 3Hit
844 0 3Fault2
924 0 2Fault3
1033 0 2Fault4
1103 0 2Hit
1233 0 2Hit
1323 0 2Hit
1413 0 1Fault2
1523 0 2Fault1
1603 0 2Hit
1713 0 1Fault2
1873 0 7Fault1
1903 0 7Hit
2013 0 1Fault7

13 page faults. LFU's weakness shows here too. Page 3 is used at steps 10 and 12, bringing its count to 2, and from step 13 on it is never used again, yet it holds its spot to the end. Because of that, pages 1, 2, and 7 keep pushing each other out in the second half, and faults continue. This is the problem of a page that was used a lot in the past hanging on.

5. Other Algorithms ​

MFU (Most Frequently Used) ​

The opposite of LFU: the most used page is evicted. The idea is that "a page used a lot has already done its job, while a page used little has only just been loaded and will be used from now on." On the reference string above it had 15 faults, the same as FIFO, and in practice it is rarely used.

Clock (Second Chance) ​

LRU is good, but accurately recording "when it was used" every time a page is used puts a heavy load on hardware. So real operating systems often use the clock algorithm, which roughly imitates LRU.

  • Each page has one reference bit. When a page is used, the hardware sets it to 1.
  • The pages are arranged in a circle like a clock face, and a hand sweeps around to find a page to evict.
  • If the page the hand points at has a reference bit of 1, it thinks "this was used recently," gives it a pass once by setting the bit to 0, and moves on. If the bit is 0, that page is evicted.
text
          ┌──── Page A (1) ────┐
          │                    │
   Page D (0)             Page B (1)     the hand points at B
          │                    │         → B is 1, so set it to 0 and move on
          └──── Page C (0) ────┘         → C is 0, so C is evicted

Running the same reference string with clock gave 14 page faults (with newly loaded pages starting with a reference bit of 1). A variant that looks at both the reference bit and the modify bit is called NUR (Not Used Recently).

Comparing the Results ​

AlgorithmPage evictedPage faults (reference string above, 3 frames)Real-world use
OPTThe one used furthest in the future9Impossible (requires knowing the future), used as a benchmark
LRUThe one unused for the longest time12Widely used (mostly as an approximation)
LFUThe least used one13Used in some caches
ClockOne whose reference bit is 014Widely used in real operating systems
FIFOThe one that came in first15Simple but performs poorly
MFUThe most used one15Almost never used

Replacement Scope: Global vs. Local Replacement ​

With multiprogramming, pages from multiple processes are loaded into memory together. So when choosing a victim, you also have to decide how far to look for candidates.

ApproachCandidatesProsCons
Global replacementPages of all processes in memoryA process that needs memory can take more, so overall throughput is highMy pages can be pushed out because of other processes, so performance can be erratic
Local replacementOnly pages of its own processNot affected by other processes, so performance is predictableEven if one process has spare frames, other processes can't use them

In practice, global replacement is more efficient, so general-purpose operating systems like Linux mainly use it. With local replacement, the number of frames each process gets is fixed, so even if some processes have frames to spare and others are short, they cannot share.

Thrashing ​

If there are too few frames compared with the pages processes are using, pages are needed again right after being evicted, over and over without end. The CPU sits almost idle waiting on the disk, and the system does nothing but page replacement. This is called thrashing.

  • Analogy: your desk is so small that as soon as you open a book, you have to return it to the stacks to make room for another, and then fetch it again, over and over.
  • Solution: reduce the number of processes running at once, or guarantee each process enough frames to hold the set of pages it has been using frequently (its working set). In the end, adding more memory is the surest fix.

Summary ​

ConceptSummary for non-CS majors
Page replacementDeciding which book to send back to the stacks when the desk is full
Victim pageThe page chosen to be evicted from memory
Page reference stringThe requested page numbers written in order (consecutive repeats merged into one)
FIFOEvicts the page that came first. Simple, but also evicts frequently used pages
Belady's anomalyWith FIFO, adding frames can increase faults
OPTEvicts the page needed furthest in the future. Best possible, but can't be used in practice because the future is unknown
LRUEvicts the page unused for the longest time. Among the best of those actually used
LFUEvicts the least used page. Has the problem of pages used heavily in the past hanging on
ClockAn LRU imitation that gives one pass via a reference bit. Widely used by real operating systems
Global / local replacementWhether to choose from all processes or only from your own process
ThrashingA state where frames are so short that the system does nothing but page replacement