Created
October 23, 2020 19:44
-
-
Save doctaphred/60540fbf429248b5c99b846b434141a5 to your computer and use it in GitHub Desktop.
"Yo dawg, I heard you like caching..."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import lru_cache | |
from types import FunctionType | |
def cache(func): | |
return lru_cache(maxsize=None)(func) | |
class Vector(tuple): | |
# [small brain] | |
def __add__(self, other): | |
return type(self)(s + o for s, o in zip(self, other)) | |
class CachedVector(Vector): | |
# [bigger brain] | |
__add__ = cache(Vector.__add__) | |
__repr__ = cache(Vector.__repr__) | |
class Key: | |
# [expanding brain] | |
def __init_subclass__(cls, /, type, **kwargs): | |
for name, attr in vars(cls).items(): | |
if isinstance(attr, FunctionType): | |
setattr(cls, name, cache(attr)) | |
cls._type = type | |
cls._keys = {} | |
cls._values = {} | |
def __new__(cls, /, *args, **kwargs): | |
value = cls._type(*args, **kwargs) | |
try: | |
return cls._keys[value] | |
except KeyError: | |
key = cls._keys[value] = super().__new__(cls) | |
cls._values[key] = value | |
return key | |
def __call__(self): | |
return self._values[self] | |
class VectorKey(Key, type=Vector): | |
# [galaxy brain] | |
def __add__(self, other): | |
return type(self)(self() + other()) | |
def __repr__(self): | |
return repr(self()) | |
def test(size): | |
v = Vector(range(size)) | |
c = CachedVector(range(size)) | |
k = VectorKey(range(size)) | |
assert v == c == k() | |
assert repr(v) == repr(c) == repr(k) | |
assert (v + v) == (c + c) == (k() + k()) == (k + k)() | |
assert type(v + v) is Vector | |
assert type(c + c) is CachedVector | |
assert type(k + k) is VectorKey | |
assert type(k() + k()) is Vector | |
assert type((k + k)()) is Vector | |
print() | |
print(f'repr (size {size})') | |
%timeit repr(v) | |
%timeit repr(c) | |
%timeit repr(k) | |
print() | |
print(f'str (size {size})') | |
%timeit str(v) | |
%timeit str(c) | |
%timeit str(k) | |
print() | |
print(f'== (size {size})') | |
%timeit v == v | |
%timeit c == c | |
%timeit k == k | |
print() | |
print(f'+ (size {size})') | |
%timeit v + v | |
%timeit c + c | |
%timeit k + k | |
%timeit (k + k)() | |
if __name__ == '__main__': | |
test(1000) | |
test(100) | |
test(10) | |
test(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preliminary results: