efficient memoize decorator?

Fredrik Lundh fredrik at pythonware.com
Sat Aug 19 01:54:55 EDT 2006


thattommyhallll at gmail.com wrote:

> all of the memoize decorators at the python cookbook seem to make my
> code slower.

if you want good performance, use the following pattern:

     def col(n, count, memo={}):
	try:
	    return memo[n, count]
         except KeyError:
	    # ... calculate value ...
	    memo[n, count] = value
             return value

for some access patterns, the following may be faster:

     def col(n, count, memo={}):
	value = memo.get((n, count))
         if value is None:
	    # ... calculate value ...
	    memo[n, count] = value
         return value

to get maximum performance, make the memo dictionary public, and make 
the check at the original call site.

> is using a decorator a lazy and inefficient way of doing memoization?

lazy, yes.  inefficient?  it depends.

</F>




More information about the Python-list mailing list