Memoization Maps and Sets
Introduction: From Clean Code to Efficient Code
In our previous lessons, we focused on the structure and safety of your code. You learned how closures allow functions to remember information and how composition lets you link small, pure functions together into pipelines. These patterns help you write code that is easy to read and maintain. However, as your applications grow, you also need to think about how your code performs when handling large amounts of data or complex calculations.
This lesson marks a shift from focusing only on how code looks to how efficiently it runs. We will explore two powerful built-in JavaScript structures: the Map and the Set. These tools will help us manage data more effectively and implement a professional performance pattern called memoization. By the end of this lesson, you will be able to store data for highly efficient access and ensure your functions never do the same hard work twice.
Understanding The Map Object
In JavaScript, we often use standard objects to store key-value pairs. While objects are useful, the Map object is specifically designed for high-performance data storage. One major advantage of a Map is that, unlike a regular object, a Map allows you to use any value as a key, including other objects or functions. It also remembers the order in which you added items, making it very predictable when you need to loop through your data.
Working with a Map involves a few core methods. You use set(key, value) to add data and get(key) to retrieve it. If you need to check whether a specific key already exists, use has(key). Additionally, you can instantly find out how many items are in your collection by checking the size property. These methods make your code more explicit and easier to read compared to the bracket notation used with standard objects.
What Is Memoization?
Memoization is a specific type of caching used to speed up computer programs. In functional programming, we know that pure functions return the same output every time they receive the same input. Because of this predictability, if a function performs a very "expensive" or time-consuming calculation, we can save the result of that calculation in a cache. The next time the function is called with the same input, we can simply return the saved result instead of running the calculation again.
This technique is especially helpful when dealing with recursive functions, which are functions that call themselves. Without memoization, a recursive function might calculate the same values thousands of times. By remembering previous results, we can turn a slow process that might take seconds into one that finishes significantly faster. It is a perfect example of using extra memory to save a significant amount of time.
