Skip to content

note: this is still the faster version #61

@earonesty

Description

@earonesty

was curious, even with the new builtin ordered dict, the simple python impl is still slower, but barely! should probably update the readme. no need to compare to old and extremely slow impls.

A = TypeVar("A")
T = TypeVar("T")

class LRU(Generic[A, T]):
    """Simple LRU cache using a dictionary."""
    def __init__(self, maxsize: int):
        self.cache = dict[Any]()
        self.maxsize = maxsize

    def get(self, key: A, default: T | None = None) -> T | None:
        if key not in self.cache:
            return default
        else:
            self.cache[key] = self.cache.pop(key)
            return self.cache[key]

    def put(self, key: A, value: int) -> None:
        self.cache[key] = value
        if len(self.cache) > self.maxsize:
            self.cache.pop(next(iter(self.cache)))

timeit

    simple = LRU(10)
    ll = lib.LRU(10)

    import timeit

    print("simple:", timeit.timeit(lambda: [simple.put(i, 1) for i in range(100)], number=10000))
    print("lru-dict:", timeit.timeit(lambda: [ll.__setitem__(i, 1) for i in range(100)], number=10000))

simple timeit results:

simple: 0.1914528000052087
lru-dict: 0.1341520000132732

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions