Suhail Gupta
Suhail Gupta

Reputation: 23206

A better way to implement in-memory-cache in javascript / nodejs

I had a question. The following code has a memory leak:

let inMemoryCache = {};

app.get("/hello",(req, resp) => {
   inMemoryCache[unixTimeStamp] = {"foo":"bar"}
   resp.json({});
});

Isn't it? The size of the object inMemoryCache will keep on increasing with each request until it hits the ceiling and the heap size explodes.

What then is the best to implement in-memory-caches?

Upvotes: 1

Views: 2080

Answers (1)

jmrk
jmrk

Reputation: 40501

Manage the size of your cache somehow. For example, you could keep a fixed number of entries, and once the cache has reached its maximum size and a new entry comes in, delete the oldest (or least frequently used, or least recently used, or some other selection criteria).

Caching is harder than it seems :-)

Upvotes: 2

Related Questions