Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Cache LRU
Cache LRU
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
Discussioni

Guida a Cache LRU · 1/6

LRU Cache Concepts

Per ora questo capitolo è disponibile solo in inglese.

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
Domande su questo capitolo?
Capitolo successivoHow 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 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.