DEV Community

Discussion on: Cache API in JavaScript - with just 20 lines of code.

Collapse
 
rouilj profile image
John P. Rouillard

Just out of curiosity why are you calling:

let currentTime = new Date();
Enter fullscreen mode Exit fullscreen mode

inside of .forEach? Why not assign it before the call:

 let currentTime = new Date();
 Object.keys(cache).forEach(key => {
            let seconds = currentTime - cache[key].time;
            ...
Enter fullscreen mode Exit fullscreen mode

this way you only pay for the overhead of calling Date once.

I expect new Date() to be practically a constant (maybe 100ms difference) over the time spent clearing the cache. Since every three seconds you are clearing anything in the cache older than 10 seconds.

Calling new Date() IIUC is expensive since it has to reach down to the operating system to get the date value.

True some item might linger in the cache for 100 ms longer but....

Collapse
 
rajeshroyal profile image
Rajesh Royal

Good correction, I will update the code.

Also I didn't write it to be optimised. I was just experimenting how caching works simply and pasted same code here 😀.

Collapse
 
milanwake profile image
Moon Presence

It's good that you shared interesting material, but remember that not all developers know, are thinking and/or working on optimizing their scripts. There are beginners, and perhaps not only beginners, who, seeing interesting code at first glance, copy it into their applications and use it without checking or optimizing, and then other people may suffer from sudden errors that can come out absolutely by accident.

It is necessary to approach operations related to cycles carefully and try to think through the work of the function in advance, since even any small error can entail a bunch of others that can cause unnecessary memory costs or something else, perhaps. Lol.

I wish you good luck.

Thread Thread
 
rajeshroyal profile image
Rajesh Royal

Sure brother.