本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

LRUキャッシュ ドキュメント
LRUキャッシュ
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
ディスカッション

LRUキャッシュ ガイド · 1/6

LRU Cache Concepts

この章は現在、英語でのみ提供しています。

A cache keeps copies of data that is expensive to fetch or compute in a smaller, faster place, so that the next request for the same data can be answered quickly. Because the fast place is small, a cache eventually fills up and has to decide what to throw away. The rule it uses is called an eviction policy, and LRU (least recently used) is the most widely taught and used one. This chapter introduces the vocabulary, compares LRU with other policies and explains when LRU is a good fit.

What a cache does

Every cache sits in front of something slower: a CPU cache in front of main memory, the OS page cache in front of the disk, Redis in front of a database, a CDN in front of an origin server. A lookup that finds the data is a hit; a lookup that has to go to the slow source is a miss. The fraction of lookups that hit is the hit ratio, and it is the number that decides whether a cache is worth having.

The simplest cache is a dictionary used for memoization. It never forgets anything, so it is only safe when the set of possible keys is small.

import time

slow_calls = 0

def slow_square(n):
    global slow_calls
    slow_calls += 1
    time.sleep(0.01)          # pretend this is a network call
    return n * n

memo = {}

def cached_square(n):
    if n in memo:             # hit
        return memo[n]
    memo[n] = slow_square(n)  # miss: compute and remember
    return memo[n]

for n in [3, 4, 3, 3, 4, 5]:
    cached_square(n)
print(slow_calls)             # 3 misses, 3 hits

Why a cache needs an eviction policy

Real caches have a capacity: a number of entries, a number of bytes or a number of memory pages. When a new item arrives and the cache is full, one existing item must be evicted. A good policy evicts the item that is least likely to be needed again soon. Nobody knows the future, so every policy is a guess based on the past.

PolicyEvictsStrengthWeakness
FIFOthe oldest inserted itemtrivial to implementignores how often or how recently an item is used
LRUthe item not used for the longest timeadapts to changing hot setsa single large scan can flush the cache
LFUthe item used the fewest timeskeeps long-term favouritesold popular items linger after they stop being used
TTLitems older than a fixed lifetimebounds stalenessnot a capacity policy on its own
Random
この章について質問がありますか?
次の章How an LRU Cache Works
a random item
no bookkeeping
unpredictable hit ratio

TTL (time to live) answers a different question from the others: not "what do we drop when full?" but "how long may data stay before it is considered stale?". Real systems often combine TTL with LRU or LFU.

A FIFO cache is easy to build with an ordered dictionary: insertion order is the eviction order, and lookups do not change it.

from collections import OrderedDict

class FIFOCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.data = OrderedDict()

    def get(self, key):
        return self.data.get(key)        # reading does not change the order

    def put(self, key, value):
        if key not in self.data and len(self.data) >= self.capacity:
            self.data.popitem(last=False)  # drop the oldest insertion
        self.data[key] = value

fifo = FIFOCache(2)
fifo.put("a", 1); fifo.put("b", 2)
fifo.get("a")
fifo.put("c", 3)                         # evicts "a" even though it was just read
print(list(fifo.data))                   # ['b', 'c']

The LRU idea

LRU relies on temporal locality: data used recently is likely to be used again soon. It keeps entries ordered by recency. Every successful get or put moves the entry to the "most recently used" end; when space is needed, the entry at the "least recently used" end is removed. Compared with FIFO, the only difference is that a read refreshes an entry. That one change makes the cache follow the current working set of a program, a user or a service.

Python ships an LRU cache as a decorator, which is the quickest way to see the policy at work.

from functools import lru_cache

@lru_cache(maxsize=2)
def load(key):
    print("loading", key)
    return key.upper()

load("a"); load("b")
load("a")                 # hit: "a" becomes most recent
load("c")                 # full: evicts "b", the least recently used
load("b")                 # miss again: prints "loading b"
print(load.cache_info())  # CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)

Vocabulary

  • Capacity: the maximum number of entries (or bytes) the cache may hold.
  • Hit / miss: whether a lookup was answered from the cache.
  • Eviction: removing an entry to make room for a new one.
  • Invalidation: removing or updating an entry because the source data changed.
  • Working set: the set of keys a workload is actively using right now.
  • Cache pollution: useful entries pushed out by data that will never be read again, typically by a one-time scan.

When LRU fits and when it does not

LRU works well when access is skewed toward a moving set of hot keys: user sessions, recently viewed pages, recently opened files. It does poorly in two situations. First, a sequential scan larger than the cache evicts everything and leaves only items that will not be reused. Second, if a few keys are popular over a long period but are touched less often than a stream of one-off keys, LFU or a hybrid such as 2Q, ARC or W-TinyLFU keeps them better. Many production systems therefore use LRU variants rather than textbook LRU.

Summary

  • A cache trades a little fast memory for fewer slow operations; the hit ratio measures how well it works.
  • When full, a cache needs an eviction policy: FIFO, LRU, LFU, random, often combined with TTL.
  • LRU evicts the entry unused for the longest time and assumes temporal locality.
  • Scans and long-term popularity are its weak spots, which is why real systems use LRU variants.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。