“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” — Wikipedia article on memoization.
Consider a simplistic example, a function that multiplies two numbers. When memoized, we identify each unique invocation with function arguments. For repeated calls, use the result from the cache. See the snippets below.
Where Do We Use Memoization?
At some point, most developers implemented caching, especially at the database level. But it’s not often done for functions. Obviously, we don’t want to cache results to multiplication. What’s a good use case for Memoization?
NgRx is an implementation of Redux for Angular. It is a popular library. Selectors are an important aspect of NgRx, which help retrieve a subset of data from the application state/store. The store is a large object as it maintains the state of the complete UI application.
Memoization is perfect for this scenario as Angular components repeatedly attempt to retrieve data from the store. This is a good use case for improving the function response times by memoizing the selectors.
Consider the following figure for understanding on how Redux and NgRx libraries work. The sample is a To-do application. The figure uses two Angular components 1. List to-dos 2. Create to-dos. For an explanation on how selectors work and their memoization feature, please following the link to the second part.