Last Updated: January 31, 2018
·
4.595K
· maciejsmolinski

Function-level cache in JavaScript

You might have already read Jose Jesus Perez Aguinaga's (@jjperezaguinaga) great post on "Function caching in Javascript".

Although his approach is really amazing, it requires you to always remember about creating the cache property that is bound to function, it might feel a bit weird. Plus, it's not really isolated, anybody might interact with the cache and pollute it with some random values.

I would suggest taking a slightly different approach - use higher-order functions. Let me show you how to do this:

var isPrime = (function () {
  var cache = {};

  return function (number) {
    // 1. if value is present in cache,
    //    return from cache
    // 2. if value is not present in cache:
    //  2.1. compute it
    //  2.2. store value in cache
    //  2.3. return comuted value
  }
}());

Simple! No need to write isPrime.cache = {}; outside the function.

But how does it work?

Because we're using self-executing anonymous function here, isPrime will immediately become the "inner" function. What's interesting here is the fact that cache variable will be available (and shared) across all function calls so it literally works the same way as Jose's example, there are no downsides.

You can benchmark both approaches and you will also see a small performance gain from using function-level cache approach shown above.

Hope you find it useful!

5 Responses
Add your response

Doesn't "self-executing anonymous function" make it less better?

over 1 year ago ·

@drabiter I don't think so, IMHO self-executing anonymous function (seaf) makes this example especially great (everything inside is encapsulated so that you could expose only the parts of API that you really want to). http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript this is also a really great example of using "seaf".

What cons of doing that do you see other than that "seaf" might look a bit weird to JavaScript newcomers and creating potential memleaks when not used wisely?

over 1 year ago ·

@maciejsmolinski I see. Thanks for the explanation and link. I'm still relative new in JS and there're some aspects that I find... make no sense compared to other languages ^^;

over 1 year ago ·

@drabiter Haha! Including self-executing anonymous functions, I totally understand you!
Here's an amazing video from Christian Johansen that may level up your JS skills: https://vimeo.com/49384334

Thanks for your comments! ;)

over 1 year ago ·

Self-executing anonymous function is in reality IIFE because there is a difference between a function declaration (FD) and a function expression (FE).

over 1 year ago ·