Memoization

Published Mar 26, 2022
Contribute to Docs

In Python, memoization can be used to improve a program’s performance.

This is ideal whenever the same calculations (with the same inputs and outputs) are known to take place. Memoization helps by saving, or caching, these results in computer memory for later use. It can be applied to many contexts, including:

  • Making calls to recursive or pure functions where some calculations use the same inputs and return the same outputs.
  • Fetching from the server with the same base API endpoints.

Syntax

memo = {}

def memo_function(args):
  if(args in memo):
    return memo[args]
  else:
    # Do this and update memo.

In Python, one way memoized results are represented is with dictionaries. In a given function, if a previously calculated result exists in the memo dictionary, it is returned. Otherwise, normal calculations take place and the memo dictionary is updated.

Example

In the example below, the get_square() function accepts a parameter n and returns the square of it. With small inputs, this function takes little to no time to process. But as the inputs get larger, the timelapse becomes more noticeable. This point is further shown with the time module.

To address this, memoization is used in the get_square_memo() function where such calculations are skipped if they have already been made and stored in memo.

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy