LRU and FIFO Are k-Competitive
Part I proved that LRU is -competitive with a phase argument (Online Problems and the Competitive Ratio). This lesson generalizes the proof to two whole classes of algorithms, marking algorithms and conservative algorithms, which together contain LRU, FIFO, CLOCK and flush-when-full; tightens it to a strict bound when the caches start empty; and shows that some natural rules, LIFO and LFU, are not competitive at all. The result is due to Sleator and Tarjan (1985); the conservative class is from Young (1994).
Phases
Fix and a request sequence . Split greedily into phases: phase 1 starts with , and each phase is the longest block of requests containing at most distinct pages. So every phase except possibly the last has exactly distinct pages, and the first request of phase is a page not requested in phase . The partition depends only on and , not on any algorithm.
Within a phase, call a page marked once it has been requested in that phase. At the start of each phase all marks are erased.
- A marking algorithm never evicts a marked page.
- A conservative algorithm misses at most times on any consecutive block of requests with at most distinct pages.
LRU is a marking algorithm: during a phase, a marked page has been requested more recently than every unmarked one, so while an unmarked page exists in the cache LRU never picks a marked one (and when all cached pages are marked, the next request is a new page and therefore starts a new phase). Flush-when-full (FWF), which empties the whole cache when it is full and a miss occurs, is also marking. FIFO is not marking, but it is conservative: on a block with at most distinct pages, a page loaded during the block stays for at least more loads, so none of the block's pages is loaded twice. LRU is conservative too.
The theorem
Theorem (Sleator and Tarjan, 1985; Young, 1994). Every marking algorithm and every conservative algorithm ALG satisfies for all when ALG and OPT start with the same cache contents. If both start with an empty cache, (strictly -competitive).
Proof
Let be the number of phases.
ALG misses at most times per phase. For a conservative algorithm this is the definition, since a phase has at most distinct pages. For a marking algorithm: once a page is requested in the phase it is marked and stays in the cache until the phase ends, so each of the phase's at most distinct pages misses at most once. Hence .
OPT misses at least once per window. For phase , let the window run from the second request of phase to the first request of phase . Let be the first request of phase . contains requests to at least distinct pages different from (the other pages of phase and the new page that starts phase ). Right after serving , OPT holds and at most other pages, so it misses at least once in . The windows are disjoint, so , which gives .
Empty start. If , ALG misses only on the first request of each distinct page, and so does OPT: . If , phase 1 has distinct pages, each a compulsory miss for OPT, all at positions before window . With windows this gives , and holds for . (For every algorithm misses on every change of page, so .)
Phases on a concrete sequence
The animation runs LRU with three slots on 20 requests. The program splits the same sequence into phases and counts the misses of LRU, FIFO and FWF in each phase; every count is at most .
def phases(reqs, k):
out, cur = [], []
for p in reqs:
if p not in cur and len(set(cur)) == k:
out.append(cur)
cur = []
cur.append(p)
return out + [cur]
def run(reqs, k, policy):
cache, misses_at = [], []
for t, p in enumerate(reqs):
if p in cache:
if policy == "lru":
cache.remove(p)
cache.append(p)
else:
misses_at.append(t)
if len(cache) == k:
if policy == "fwf":
cache = [] # flush everything
else:
cache.pop(0) # lru: least recent; fifo: oldest load
cache.append(p)
return misses_at
reqs = "A B A C D A B D C E C A B E D B A C A E".split()
k = 3
ph = phases(reqs, k)
starts = [sum(len(x) for x in ph[:i]) for i in range(len(ph))]
print("phases:", " | ".join(" ".join(x) for x in ph))
for policy in ["lru", "fifo", "fwf"]:
m = run(reqs, k, policy)
per = [sum(s <= t < s + len(x) for t in m) for s, x in zip(starts, ph)]
print(f"{policy.upper():4} {len(m):2} misses, per phase {per}")
print(f"{len(ph)} phases: OPT >= {len(ph) - 1} after the first, and ALG <= k * phases = {k * len(ph)}")phases: A B A C | D A B D | C E C A | B E D B | A C A E
LRU 14 misses, per phase [3, 2, 3, 3, 3]
FIFO 14 misses, per phase [3, 3, 3, 2, 3]
FWF 15 misses, per phase [3, 3, 3, 3, 3]
5 phases: OPT >= 4 after the first, and ALG <= k * phases = 15
The phases contain exactly 3 distinct pages each (the last one may have fewer). FWF is the crudest marking algorithm, and here it misses exactly 3 times per phase; LRU and FIFO sometimes keep a page from the previous phase that is requested again.
In C++
LRU in per request (a list ordered by recency plus a hash map from pages to list positions), the standard way to implement it; practise the same structure in LRU Cache. The program checks the strict bound and the per-phase bound on a long seeded sequence over 10 pages.
#include <cstdio>
#include <list>
#include <random>
#include <set>
#include <unordered_map>
#include <vector>
struct LRU {
int k;
std::list<int> order; // front = most recent
std::unordered_map<int, std::list<int>::iterator> pos;
bool access(int p) { // returns true on a miss
auto it = pos.find(p);
bool miss = it == pos.end();
if (!miss) order.erase(it->second);
else if ((int)pos.size() == k) { pos.erase(order.back()); order.pop_back(); }
order.push_front(p);
pos[p] = order.begin();
return miss;
}
};
int opt(const std::vector<int>& r, int k) {
int n = r.size(), misses = 0;
std::vector<int> nxt(n);
std::unordered_map<int, int> seen;
for (int t = n - 1; t >= 0; --t) { nxt[t] = seen.count(r[t]) ? seen[r[t]] : n + r[t]; seen[r[t]] = t; }
std::set<std::pair<int, int>> s;
std::unordered_map<int, int> key;
for (int t = 0; t < n; ++t) {
if (key.count(r[t])) s.erase({key[r[t]], r[t]});
else {
++misses;
if ((int)key.size() == k) { auto f = std::prev(s.end()); key.erase(f->second); s.erase(f); }
}
key[r[t]] = nxt[t];
s.insert({nxt[t], r[t]});
}
return misses;
}
int main() {
std::mt19937 rng(5);
std::vector<int> r(5000);
for (int& p : r) p = rng() % 10;
for (int k : {2, 4, 6, 8}) {
LRU cache{k, {}, {}};
int misses = 0, worst_phase = 0, in_phase = 0;
std::set<int> distinct;
for (int p : r) {
if (!distinct.count(p) && (int)distinct.size() == k) { distinct.clear(); in_phase = 0; }
distinct.insert(p);
if (cache.access(p)) { ++misses; ++in_phase; }
if (in_phase > worst_phase) worst_phase = in_phase;
}
int o = opt(r, k);
std::printf("k = %d: LRU %4d, OPT %4d, ratio %.3f, k * OPT = %5d, most misses in a phase %d\n",
k, misses, o, double(misses) / o, k * o, worst_phase);
}
}k = 2: LRU 3978, OPT 3179, ratio 1.251, k * OPT = 6358, most misses in a phase 2
k = 4: LRU 2981, OPT 1805, ratio 1.652, k * OPT = 7220, most misses in a phase 4
k = 6: LRU 1997, OPT 971, ratio 2.057, k * OPT = 5826, most misses in a phase 6
k = 8: LRU 996, OPT 394, ratio 2.528, k * OPT = 3152, most misses in a phase 8
Not every rule is competitive
Two rules that sound reasonable have no bounded ratio.
- LIFO (evict the page loaded most recently): with pages , request , then alternate . LIFO evicts to load and then to load , missing on every request, while OPT misses once.
- LFU (evict the least frequently requested page): request each of pages many times ( times each), then alternate between two fresh pages and , times each. LFU keeps the heavy pages forever and evicts for and for , missing on every alternating request, while OPT evicts the dead heavy pages once.
def simulate(reqs, k, policy):
cache, freq, loaded, misses = [], {}, {}, 0
for t, p in enumerate(reqs):
freq[p] = freq.get(p, 0) + 1
if p in cache:
continue
misses += 1
if len(cache) == k:
if policy == "lifo":
victim = max(cache, key=lambda q: loaded[q])
else: # lfu, ties: oldest load
victim = min(cache, key=lambda q: (freq[q], loaded[q]))
cache.remove(victim)
cache.append(p)
loaded[p] = t
return misses
def opt(reqs, k):
cache, misses = set(), 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
rest = reqs[t + 1:]
cache.remove(max(cache, key=lambda q: rest.index(q) if q in rest else len(rest)))
cache.add(p)
return misses
k = 4
for N in [10, 50, 200]:
lifo_seq = list(range(1, k + 1)) + [k + 1, k] * N
lfu_seq = [p for p in range(1, k) for _ in range(N + 1)] + ["a", "b"] * N
print(f"N = {N:3}: LIFO {simulate(lifo_seq, k, 'lifo'):4} vs OPT {opt(lifo_seq, k)} "
f"LFU {simulate(lfu_seq, k, 'lfu'):4} vs OPT {opt(lfu_seq, k)}")N = 10: LIFO 24 vs OPT 5 LFU 23 vs OPT 5
N = 50: LIFO 104 vs OPT 5 LFU 103 vs OPT 5
N = 200: LIFO 404 vs OPT 5 LFU 403 vs OPT 5
The online cost grows linearly with while OPT stays constant, so no constant works. Both rules violate the marking property: they evict a page requested in the current phase while keeping one that is not.
Test yourself
Which of these is a marking algorithm?
- FIFO
- LRU
- LIFO
- LFU
In the phase argument, why does OPT miss at least once in each window ?
- Because every phase starts with a miss for every algorithm
- Because the window requests at least distinct pages other than the phase's first page , and OPT holds plus only others
- Because OPT is lazy
- Because LRU misses times
A request sequence splits into 40 phases for . What is the best upper bound on the misses of a marking algorithm, and the lower bound on OPT?
- and
- and
- and
- and
Why is LFU not competitive?
- It is randomized
- Pages that were popular long ago keep high counts and are never evicted, so an alternation between two new pages misses every time
- It uses too much memory
- It is a marking algorithm