Created
October 16, 2013 18:16
-
-
Save davidchambers/7012316 to your computer and use it in GitHub Desktop.
The right approach to memoization: keep it separate
This file contains hidden or 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
import time | |
def memoize(f): | |
memo = {} | |
def wrapper(*args): | |
if args not in memo: | |
memo[args] = f(*args) | |
return memo[args] | |
return wrapper | |
def _identity(x): | |
time.sleep(0.05) # simulate expensive operation | |
return x | |
identity = memoize(_identity) | |
if __name__ == '__main__': | |
import timeit | |
for desc, name in (('original', '_identity'), ('memoized', 'identity')): | |
print('{}: {}'.format(desc, timeit.timeit('{}(42)'.format(name), | |
setup='from __main__ import {}'.format(name), number=100))) |
Author
davidchambers
commented
Oct 16, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment