Last week at work, we implemented a caching mechanism for Chargebee API calls to avoid API restrictions with Chargebee. This meant we could memorize the result of an API call in our persistent store. This yielded two advantages:
This made me curious about what an implementation would look like in native JavaScript. Turns out it can be quite simple. My naive approach was to first serialize the expensive function and its dependencies (arguments). This is a similar concept to React's useMemo
hook. From there, use the serialized string as its unique identifier (or key). Every time the same combination of the function and its arguments is encountered again, we check the cache for the same key and return the result from the cache.
This is what this may look like:
Now we need to create an expensive function that takes time to complete to test on our runMemo
function.
To run the expensive function against the cache, we create 3 runs:
These were the results from my local machine:
As we can see, the cache behaved as we expected and we saved a good 7 seconds on Run B. This is of course a very basic implementation of a cache. Building upon this, we could make the following improvements:
The full runnable code can be found here: