Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

LRU cache docs
LRU cache
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
Discussions

LRU cache guide · 4/6

Complexity of an LRU Cache

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
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.
Questions about this chapter?
Previous chapterImplementing an LRU CacheNext chapterLRU Practice Problems

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.