lru-dict icon indicating copy to clipboard operation
lru-dict copied to clipboard

note: this is still the faster version

Open earonesty opened this issue 2 months ago • 0 comments

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

earonesty avatar Apr 05 '24 17:04 earonesty