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 · 4/6

Complexity of an LRU Cache

Per ora questo capitolo è disponibile solo in inglese.

The hash map plus doubly linked list design makes every operation constant time on average. This chapter explains where that bound comes from, what it costs in memory, how simpler designs compare, and why hit ratio matters as much as Big-O.

Time per operation

OperationHash map partList partTotal
get (hit)lookup O(1) averageunlink + push front O(1)O(1) average
get (miss)lookup O(1) averagenothingO(1) average
put (update)lookup O(1) averageunlink + push front O(1)O(1) average
put (insert, not full)insert O(1) amortizedpush front O(1)O(1) amortized
put (insert, full)delete + insert O(1) averageunlink tail + push front O(1)O(1) amortized

The list operations are O(1) in the worst case because each changes at most four pointers. The hash map is O(1) on average; with pathological collisions a lookup can degrade to O(n), and resizing makes insertion amortized rather than strictly constant. In practice, with a decent hash function, every operation is a handful of memory accesses.

Space

The cache holds at most capacity entries, so space is O(capacity). The constant factor is larger than for a plain dict: each entry needs a map slot, a node object, two pointers and a second reference to the key. You can see the overhead in Python:

import sys

class Node:
    __slots__ = ("key", "value", "prev", "next")

class FatNode:
    def __init__(self):
        self.key = self.value = self.prev = self.next = None

slim, fat = Node(), FatNode()
print(sys.getsizeof(slim))                            # e.g. 64 bytes
print(sys.getsizeof(fat) + sys.getsizeof(fat.__dict__))  # noticeably more

Exact numbers depend on the Python version, but __slots__ consistently saves memory per node. OrderedDict and functools.lru_cache keep their links in C, which is cheaper still.

Why simpler designs are slower

Many first attempts keep keys in a plain list and move them around. Finding and removing a key in a Python list costs O(n), so each operation becomes linear.

class NaiveLRU:
    def __init__(self, capacity):
        self.capacity = capacity
        self.order = []          # least recent first
        self.data = {}

    def get(self, key):
        if key not in self.data:
            return None
        self.order.remove(key)   # O(n) search and shift
        self.order.append(key)
        return self.data[key]

    def put(self, key, value):
        if key in self.data:
            self.order.remove(key)
        elif len(self.data) >= self.capacity:
            del self.data[self.order.pop(0)]  # O(n) shift
        self.order.append(key)
        self.data[key] = value
Domande su questo capitolo?
Capitolo precedenteImplementing an LRU CacheCapitolo successivoLRU Practice Problems
Designgetput / evictNotes
list of keys + dictO(n)O(n)simple, fine for tiny caches
dict + timestamps, scan for minimumO(1)O(n)eviction scans all entries
dict + min-heap of timestampsO(log n)O(log n)needs lazy deletion of stale heap items
dict + doubly linked listO(1)O(1)the standard design
OrderedDict / LinkedHashMap / JS MapO(1)O(1)the same design, provided by the library

A small benchmark makes the difference visible as the capacity grows.

import random
import timeit
from collections import OrderedDict

def ordered_ops(capacity, keys):
    cache = OrderedDict()
    for k in keys:
        if k in cache:
            cache.move_to_end(k)
        else:
            cache[k] = k
            if len(cache) > capacity:
                cache.popitem(last=False)

def naive_ops(capacity, keys):
    order, data = [], set()
    for k in keys:
        if k in data:
            order.remove(k)
        elif len(order) >= capacity:
            data.discard(order.pop(0))
        order.append(k)
        data.add(k)

keys = [random.randrange(4000) for _ in range(20000)]
for name, fn in [("OrderedDict", ordered_ops), ("list", naive_ops)]:
    seconds = timeit.timeit(lambda: fn(2000, keys), number=1)
    print(f"{name:12} {seconds:.3f}s")

Comparison with other policies

PolicyTypical implementationCost per operation
FIFOqueue + dictO(1)
LRUdict + doubly linked listO(1)
LFUdict + frequency buckets of linked listsO(1); O(log n) with a heap
TTLdict + expiry time, checked on readO(1) lazily; periodic sweeps cost O(n)
CLOCK (LRU approximation)circular array + reference bitsO(1) amortized

CLOCK and sampled LRU exist because true LRU updates shared pointers on every read, which is expensive for hardware and for highly concurrent software. They give up exact recency order in exchange for cheaper hits.

Hit ratio matters more than Big-O

All good designs are O(1); what differs in practice is the hit ratio. A useful property of LRU is that it is a stack algorithm: for the same request sequence, a larger LRU cache never has more misses than a smaller one. FIFO does not have this property (Belady's anomaly). Measure the hit ratio on a realistic workload before choosing a capacity.

Summary

  • get and put are O(1) on average; the list part is O(1) in the worst case.
  • Space is O(capacity) with a per-entry overhead for nodes and pointers.
  • List-based or scan-based designs are O(n); heap-based designs are O(log n).
  • Choose capacity and policy by measured hit ratio, not only by complexity.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.