EDDYMENS

Published 2 months ago

What Is Memoization?

Table of contents

Definition

Memoization is a technique in programming used to make your code run faster by storing the results of expensive function calls. Think of it as a memory bank where you store answers to problems you've already solved, so you don't have to solve them again. This technique is especially useful when dealing with functions that are called repeatedly but then the outputs remain the same given the same inputs.

To explain it with an analogy, imagine you're a math teacher. One of your students keeps asking you the same question over and over. Instead of solving it every time, you write the answer on the board, and the next time they ask, you just point to it. A bit rude but that's what memoization does, it saves the answer and gives it back instantly the next time it's needed.

Example

Let's look at a simple example in JavaScript. Say we want to calculate the Fibonacci sequence, where each number is the sum of the two preceding ones (1, 1, 2, 3, 5, 8, and so on). Without memoization, you might end up recalculating the same values over and over, making your program slow.

Here’s what it would look like without memoization:

Without Memoization

01: function fibonacci(n) { 02: if (n <= 1) return n; 03: return fibonacci(n - 1) + fibonacci(n - 2); 04: }

This code works, but it recalculates Fibonacci numbers multiple times. For example, to calculate fibonacci(5), it calculates fibonacci(3) twice. Memoization can help us avoid this repetition:

With Memoization

01: function fibonacciMemo(n, memo = {}) { 02: if (n in memo) return memo[n]; 03: if (n <= 1) return n; 04: memo[n] = fibonacciMemo(n - 1, memo) + fibonacciMemo(n - 2, memo); 05: return memo[n]; 06: }

In this version, we store the results of fibonacciMemo(n) in the memo object, so each number is calculated only once. This way, your code runs faster, especially for large inputs.

Conclusion

Memoization is a simple yet powerful optimization technique that can improve the performance of your programs. By storing previously computed results, you save time and computing resources.

The downside is that memoization uses extra memory, so it’s important to find a good balance between saving time and using memory efficiently.

Here is another article you might like 😊 What Is A Broadcast Receiver In Android Development?