Skip to content
Advertisement

How long does a static class member stay in memory in javascript?

Say I have a class like so:

class KeyStorage {
  // unrelated functionality omitted 
  static Keys = {}; // contains a bunch of "key" related objects
  static #foundKeys = {};

  static #getKey(name, ensureValid = true) {
    let foundKey = this.#foundKeys[name];
    if (foundKey && foundKey.key.id === name) {
      this.#log("getKey", name, foundKey, "FOUND IN HASH TABLE");
      this.#foundKeys[name].requestCount++;
      return foundKey;
    }
    for (let storageKey in KeyStorage.Keys) {
      const key = KeyStorage.Keys[storageKey];
      if (key.id === name) {
        foundKey = key;
        this.#log("getKey", name, foundKey, "FOUND IN LOOP");
        break;
      }
    }
    if (ensureValid) ArgumentNullError.Guard("foundKey", foundKey);
    this.#foundKeys[name] = { key: foundKey, requestCount: 1 };
    return foundKey;
  }
}

As you can see, when looking for a key I first check the #foundKeys property to see if I’ve already looked for it before, if not I look for it then add it to the #foundKeys object at the end if so. My question is, how long does the application keep that object in memory?

The class is heavily used so I can’t see a reason garbage collection would kick in while the application is still accessing the object, but I haven’t found any info relating to this. Is “caching” non-sensitive and relatively unimportant data in this way a bad practice?

In the case of this class, it isn’t massively important I keep the object alive for the entire life of the application, it’s just to boost performance by avoiding constantly looping for a key if I’ve already found it recently, but it’d be good to know when to avoid doing this as I’ve considered the same approach for other issues but I’m not sure what the risks would be, if any.

Answer

How long does a static class member stay in memory in javascript?

As long as the class itself stays in memory. Which usually is the entire lifetime of the application.

Advertisement