Skip to content

Instantly share code, notes, and snippets.

@KeyurRamoliya
Created September 23, 2023 06:06
Show Gist options
  • Save KeyurRamoliya/c9a63607e40c66cd22a20d7cad6f61b0 to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/c9a63607e40c66cd22a20d7cad6f61b0 to your computer and use it in GitHub Desktop.
Optimize Performance with Memoization

Optimize Performance with Memoization

Memoization is an advanced technique used to optimize the performance of functions by caching the results of expensive or time-consuming computations. By storing previously calculated results, you can avoid redundant calculations and improve the efficiency of your code.

Here's a basic example of memoization:

// Without memoization
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}
var startTime = performance.now();
console.log(fibonacci(45)); // 1134903170
var endTime = performance.now();
var executionTime = endTime - startTime;
console.log(executionTime); // Around 15000 ms

// With memoization
const memo = {};
function fibonacciWithMemoization(n) {
    if (n <= 1) return n;
    if (memo[n]) return memo[n];
    memo[n] = fibonacciWithMemoization(n - 1) + fibonacciWithMemoization(n - 2);
    return memo[n];
}

startTime = performance.now();
console.log(fibonacciWithMemoization(45)); // 1134903170
endTime = performance.now();
executionTime = endTime - startTime;
console.log(executionTime); // Around 0.5 ms

In this example, the fibonacciWithMemoization function caches the results of Fibonacci calculations in the memo object, which prevents redundant calculations.

Key points about memoization:

  1. Caching Results: Memoization stores computed results in memory, allowing the function to return those results when the same inputs are encountered again.

  2. Pure Functions: Memoization is most effective with pure functions, which produce the same output for the same input. This property ensures that cached results remain valid.

  3. Efficiency: Memoization can significantly improve functions' performance involving expensive computations, recursive algorithms, or complex calculations.

  4. Memory Usage: Be mindful of memory usage, especially when memoizing functions with many possible inputs. You may need to implement mechanisms to limit the cache size or use libraries like lru-cache to manage it.

  5. Function Composition: You can compose memoized functions to build more complex, efficient operations. This is especially useful in functional programming.

Memoization is a powerful technique for optimizing the performance of your JavaScript applications, particularly in situations where you need to compute values that are expensive to calculate or are repeatedly requested with the same inputs. However, it's essential to use it judiciously, as excessive caching can lead to increased memory usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment