I am trying to find the best caching solution for a node app. There a few modules which can manage this. Most popular being: https://www.npmjs.com/package/node-cache
But I found that responses are faster if I just save some results into a variable like:
var cache = ["Kosonsoy","Pandean","Ḩadīdah","Chirilagua","Chattanooga","Hebi","Péruwelz","Pul-e Khumrī"];
I can then update that variable on a fixed interval, is this also classed as caching? Are there any known issues/problems to this method. As it defiantly provides the fastest response times.
const express = require('express'); const fetch = require('node-fetch'); const NodeCache = require('node-cache'); // stdTTL is the default time-to-live for each cache entry const myCache = new NodeCache({ stdTTL: 600 }); // retrieve some data from an API async function getPosts() { const response = await fetch(`https ...
Of course it is faster as you use local memory to store the data. For limited cache size this is good, but can quickly eat up all your process memory.
I would advise to use modules as there is a considerable amount of collaborative brainpower invested in them. Alternatively you can use a dedicated instance to run something like Redis to use as cache.
Alternatives aside, if you would stick with your solution I recommend small improvement.
Instead of
var cache = ["Kosonsoy","Pandean","Ḩadīdah","Chirilagua","Chattanooga","Hebi","Péruwelz","Pul-e Khumrī"];
try using objects as key value storage.
This will make searching and updating entries faster.
var cache = {"Kosonsoy":data,"Pandean":moreData,...};
Searching in array requires iterations while accessing the object is as simple as
var storedValue = cache["Kosonosoy"];
saving
cache[key] = value;
If you use many workers you will have a duplicated cache for each one because they have no shared memory.
Of course, you can use it for small data. And keeping a data in a variable for an amount of time can be called caching for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With