https://en.wikipedia.org/wiki/Memoization
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
在计算过程中,结果缓存记忆是一种程序设计优化技术:通过缓存已经计算过的结果,当再次执行相同的计算时直接返回已有结果,这样可以加速耗费时间成本的函数或者是反复执行的递归函数的执行速度。
import time
def expensive_func(num):
print("Computing {}...".format(num))
time.sleep(1) # to mimic expensive computing
return num*num
result = expensive_func(4)
print result
result = expensive_func(100)
print result
# 由于未使用memoization技术,所以再次计算时,
# 依然会消耗与第一次计算相同的时间成本
result = expensive_func(4)
print result
result = expensive_func(100)
print result
设置一个ef_cache字典,如果是第一次计算,则把参数与结果保存在字典中;如果是第二次计算,则参数会命中字典,直接返回已经计算出的结果。
import time
ef_cache = {}
def expensive_func(num):
# if already calculated,
# return the result directly.
if num in ef_cache:
print("hit cache with num: {}".format(num))
return ef_cache[num]
print("Computing {}...".format(num))
time.sleep(1) # to mimic expensive computing
result = num * num
# cache the result
ef_cache[num] = result
return result
result = expensive_func(4)
print(result)
result = expensive_func(100)
print(result)
# 由于使用memoization技术,所以再次计算时,
# 可以直接“命中缓存”,返回结果
result = expensive_func(4)
print(result)
result = expensive_func(100)
print(result)