Science Knowings: JavaScript Course For Social Media


From Function Currying to Memoization

We've explored function currying, a technique for creating new functions from existing ones. Now, let's dive into another powerful concept: memoization!

What is Memoization?

Memoization is an optimization technique that stores the results of expensive function calls so that subsequent calls with the same inputs can be served from the cache, improving performance.

Benefits of Memoization

  • Improved Performance: By caching results, memoization eliminates the need for recomputation, leading to significant speed improvements.
  • Reduced Computational Time: Saves time by skipping unnecessary calculations.
  • Memory Optimization: Caching results can reduce memory usage by avoiding redundant storage.

How Does Memoization Work?

  1. Function Invocation: When a memoized function is called with specific inputs.
  2. Cache Check: The function checks a cache (usually a hashmap) for the result with the given inputs.
  3. Result Return: If the result is found in the cache, it is returned immediately without recomputation.
  4. Computation and Caching: If the result is not in the cache, the function computes the result, stores it in the cache, and returns it.

Techniques for Memoization

  • Table Lookup: Using a hash table to store input-output pairs.
  • Closure: Creating a closure to access the memoized results.
  • Decorator: Using a function decorator to wrap the original function and memoize its results.

Memoization in JavaScript

const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = args.toString();
    if (key in cache) return cache[key];
    const result = fn(...args);
    cache[key] = result;
    return result;

Memoizing in React

import { useMemo } from 'react';
const MyComponent = () => {
  const memoizedValue = useMemo(() => {
    return computeExpensiveValue();
  }, []);
  // ...

Memoization in Redux

import { createSelector } from 'reselect';
const memoizedSelector = createSelector(
  [state => state.items],
  items => items.filter(item => item.isAvailable)

Memoization in Python

from functools import lru_cache
def fibonacci(n):
  if n < 2:
    return n
  return fibonacci(n-1) + fibonacci(n-2)

Memoization in Java

import java.util.HashMap;
class Memoizer<T, R> {
  private final HashMap<T, R> cache = new HashMap<>();
  public R memoize(T key, Supplier<R> supplier) {
    return cache.computeIfAbsent(key, k -> supplier.get());

Next Topic: Recursion

Recursion is the process of defining a function in terms of itself. It's a powerful technique for solving complex problems by breaking them down into smaller versions. Stay tuned to explore recursion and its practical applications in our next session!