“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

I’ve written a two part article in Memoization in JavaScript. The first part explains the concept with basic implementation in JavaScript code. It details a way to apply the technique on function calls. It is generic to handle most JavaScript functions.

Basics

A comprehensive read on Memoization in JavaScript.

Memoization caches function responses. Long-running JavaScript functions, when memoized, return the response from the cache. The first time the function is run, it saves the result in a key-value pair. 

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.

Follow the link for a complete explanation of the memoization technique in JavaScript.

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

Memoization with Selectors in NgRx

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. 

Thanks for the quick read; I would appreciate if you can provide feedback. An easy way to connect with me is on Twitter @keertikotaru. More about me on my web page, here.





Source link

Write A Comment