LRU cache
Rob Cliffe
rob.cliffe at btinternet.com
Sat Feb 18 19:17:02 EST 2023
On 18/02/2023 17:19, Albert-Jan Roskam wrote:
>
>
> On Feb 18, 2023 17:28, Rob Cliffe via Python-list
> <python-list at python.org> wrote:
>
> On 18/02/2023 15:29, Thomas Passin wrote:
> > On 2/18/2023 5:38 AM, Albert-Jan Roskam wrote:
> >> I sometimes use this trick, which I learnt from a book by
> Martelli.
> >> Instead of try/except, membership testing with "in"
> >> (__contains__) might
> >> be faster. Probably "depends". Matter of measuring.
> >> def somefunc(arg, _cache={}):
> >> if len(_cache) > 10 ** 5:
> >> _cache.pop()
> >> try:
> >> return _cache[arg]
> >> except KeyError:
> >> result = expensivefunc(arg)
> >> _cache[arg] = result
> >> return result
> >> Albert-Jan
> >
> > _cache.get(arg) should be a little faster and use slightly fewer
> > resources than the try/except.
> >
> Provided that you can provide a default value to get() which will
> never
> be a genuine "result".
>
>
> =====
>
> This might be better than None:
> _cache.get(arg, Ellipsis)
>
>
A common strategy is to have a dedicated sentinel object. E.g. (untested):
IMPOSSIBLE_RESULT = object()
...
if _cache.get(arg, IMPOSSIBLE_RESULT) == IMPOSSIBLE_RESULT:
# arg was not in the cache
...
More information about the Python-list
mailing list