DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • In-Depth Guide to Using useMemo() Hook in React

Trending

  • Testing SingleStore's MCP Server
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Software Design and Architecture
  3. Performance
  4. Understanding JavaScript/TypeScript Memoization

Understanding JavaScript/TypeScript Memoization

Reduce function time complexity with one simple concept.

By 
Carlos Caballero user avatar
Carlos Caballero
·
Aug. 15, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
10.5K Views

Join the DZone community and get the full member experience.

Join For Free

Memoization is a programming technique that allows users to reduce a function’s time cost for space cost. That is, functions that are memoized gain speed for higher use of memory space.

In the following animation, you can see the final result of applied memoization in our code.

Running without memoization

What Is a Pure Function?

Memoization can only be done in pure functions. A pure function must meet the following criteria:

  • It is a function that always returns the same result when the arguments are the same. For example, the following functions are impure:
    • Functions that use random numbers.
    • Functions that use DateTime to generate the result.
  • It is a function that does not produce side effects in the application:
    • Data mutation or change application state.
    • Network request.
    • Database or file request.
    • Obtaining user input.
    • Querying the DOM.

Benefits

Pure functions are used in web development due for several reasons:

  • Code is more declarative. Also, pure functions focus on how different inputs are related to outputs.
  • Code is more easily tested, and finding bugs is easier when compared to impure functions.

Pure Functions Example

Recursive functions frequently use pure functions; the most classical recursive problem is the factorial.

Recursive factorial function

The imperative version of the function factorial is pure too. In both cases, when the input is the same, the output will be the same.

Imperative factorial function

Another interesting example of pure functions are the following:

Pure function

Memoization in Recursive Functions

Memoization is a programming technique that allows the output of a pure function to be stored in cache, so the same function call does not need to be computed again. For example, if you calculate the value of factorial(1), you can store the return value 1, and the same action can be done in each execution. So, when you run the factorial(100), execution may take a while the first time, but the second time, runtime will be reduced.

Memoization Example

In this section, I'm going to show you how to implement memoization using the closure and decorator patterns in JavaScript.

The decorator pattern allows you to add new features to any object in runtime using composition instead of hierarchy. The goal is to avoid creating a class hierarchy of our features.

So, a basic implementation of memoizing a decorator in JavaScript is shown below:

Memoizing a decorator
  1. We define the cache in which the execution’s result will be stored. We use a map to store these results.
  2. The decorator returns a new function that has the same behavior as the original function, but memoization is implemented.
  3. The key of the key-value map is generated using stringify and args from the original function.
  4. The execution of the original function (fn(...args)) decides whether there is a store in the cache.
  5. The value is stored in the cache (whether there is pre-calculated previously).
  6. The result is returned.

How to Use the Memoized Decorator

The way to use this decorator using JavaScript is very easy:

Memoized decorator

In this case, the add function is the original function without memoization, and the addMemoized function is a new function that implements memoization using the decorator pattern.

Demo Using Memoization

Now, I’m going to show you a real demo using memoization. Imagine a horribly programmed algorithm that indicates if an array has a unique value (as the Array.prototype.some).

Finding unique values in an array

The following step runs the original code and the memoized code to compare the time used in each function. It is very important to remember that the original code is not modified, except for the addition of memoization.

The following function is used to measure the time used in each execution.

Measuring time of execution

The arrays are generated at the beginning of the script:

Responsive execution

Finally, when the user clicks a button, the functions are executed.

1. No Memoization

Call without memoization

2. Memoization

Call with memoization

The result is shown in the following animation:

Final results

The GitHub project is available here.

Memoization

Published at DZone with permission of Carlos Caballero. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • In-Depth Guide to Using useMemo() Hook in React

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!