Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de Cache LRU
Cache LRU
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
Discussões

Guia de Cache LRU · 2/6

How an LRU Cache Works

Por enquanto, este capítulo está disponível apenas em inglês.

An LRU cache has to answer two questions quickly: "is this key in the cache?" and "which key was used least recently?". No single classic data structure answers both in constant time, so the standard design combines two: a hash map for lookup and a doubly linked list for recency order. This chapter walks through that design and traces it on a small example.

Two structures working together

  • The hash map maps each key to its node in the list, so finding an entry is O(1) on average.
  • The doubly linked list keeps the entries in recency order. The front (next to head) is the most recently used entry; the back (next to tail) is the least recently used.
  • Each node stores its key as well as its value. On eviction we only have the node at the back, and we need its key to delete it from the map.
  • The list is doubly linked because removing a node from the middle needs its predecessor. With prev and next pointers, unlinking takes O(1).
  • Two sentinel nodes, head and tail, never hold data. They remove every special case for an empty list or for the first and last node.
head <-> [C] <-> [B] <-> [A] <-> tail
         most recent      least recent

map: { A: node A, B: node B, C: node C }

The operations

A get(key) looks the key up in the map. On a miss it returns a sentinel value such as -1 or None. On a hit it unlinks the node and inserts it right after head, then returns the value.

A put(key, value) first checks the map. If the key exists, it updates the value and moves the node to the front, exactly like a hit. Otherwise, if the cache is full, it removes the node just before tail and deletes that node's key from the map; then it creates a new node, inserts it after head and stores it in the map.

All pointer work reduces to two helpers. Each touches a constant number of pointers, which is why both operations are O(1).

def unlink(node):
    # A <-> node <-> B  becomes  A <-> B
    node.prev.next = node.next
    node.next.prev = node.prev

def push_front(head, node):
    # head <-> X  becomes  head <-> node <-> X
    node.prev = head
    node.next = head.next
    head.next.prev = node
    head.next = node

Moving a node to the front is simply unlink(node) followed by push_front(head, node). Evicting is unlink(tail.prev) plus a map deletion.

A trace with capacity 3

The list is written from most recent to least recent.

Dúvidas sobre este capítulo?
Capítulo anteriorLRU Cache ConceptsPróximo capítuloImplementing an LRU Cache
StepOperationResultList after the stepNote
1put(A, 1)-Ainsert
2put(B, 2)-B, Ainsert
3put(C, 3)-C, B, Acache is now full
4get(A)1A, C, Bhit: A moves to the front
5put(D, 4)-D, A, Cfull: B is evicted
6get(B)-1D, A, Cmiss: order unchanged
7put(C, 30)-C, D, Aupdate: C moves to the front
8put(E, 5)-E, C, Dfull: A is evicted
9get(D)4D, E, Chit

Step 5 is the key moment. A was inserted first, so a FIFO cache would have evicted it. Because step 4 read A, LRU evicts B instead. Step 6 shows that a miss changes nothing, and step 7 shows that an update counts as a use.

Reproducing the trace

The quickest way to check a trace is a short simulation with OrderedDict, which already provides the two primitives we need: move_to_end and popitem(last=False).

from collections import OrderedDict

def run(capacity, ops):
    cache = OrderedDict()            # first = least recent, last = most recent
    for op, key, *value in ops:
        result = "-"
        if op == "get":
            if key in cache:
                cache.move_to_end(key)
                result = cache[key]
            else:
                result = -1
        else:
            if key in cache:
                cache.move_to_end(key)
            elif len(cache) >= capacity:
                cache.popitem(last=False)
            cache[key] = value[0]
        order = ", ".join(reversed(cache))  # most recent first
        print(f"{op}({key}) -> {result}: {order}")

run(3, [("put", "A", 1), ("put", "B", 2), ("put", "C", 3), ("get", "A"),
        ("put", "D", 4), ("get", "B"), ("put", "C", 30), ("put", "E", 5), ("get", "D")])

The last printed line is get(D) -> 4: D, E, C, matching the table.

Common mistakes in the walkthrough

  • Forgetting to move the node on a get. The cache then behaves like FIFO.
  • Forgetting to move the node when put updates an existing key.
  • Evicting before checking whether the key already exists. Updating a key in a full cache must not evict anything.
  • Removing the node from the list but not from the map (or the reverse). The two structures must always describe the same set of keys.

Summary

  • The map gives O(1) lookup; the doubly linked list gives O(1) reordering and eviction.
  • Sentinels head and tail remove edge cases; nodes keep their key so eviction can clean up the map.
  • Hits and updates move an entry to the front; misses change nothing; eviction removes the node before tail.

0 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.