DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

4 2

Javascript: Memoization

Memoization is a technique used to save execution time by caching results of frequently used function.

Consider we have a function defined for let's say calculating area of square. Within duration of program execution function needs to be called 'n' number of times. Each time function gets called area of square is computed based on arguments passed and result is returned. It takes lot of execution time to compute area each time and return output. Here, we can make use of Memoization technique to cache result and later use the cache result instead of computing each time.

Take a look at below example.

Alt Text

Here loop runs 100 times which causes function to be called 100 times and each time area is calculated.

Now look at below example.

Alt Text

Here loop runs 100 times which causes function to be called 100 times and only once area will be computed for rest 99 times saved value will be returned.

If we look first example takes longer time than the second example. Consider multiple lines of complex computation functionality, in that case obviously Memoization will save lots of execution time.

Happy Coding!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay