Skip to content

Commit

Permalink
Revise cache internals
Browse files Browse the repository at this point in the history
Now cache initialization and `get()` is less costly to use and it shifts the weight to `set()`.

PR #20430.
  • Loading branch information
Chocobo1 committed Feb 18, 2024
1 parent 63c9b63 commit bb8a012
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/webui/www/private/scripts/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ window.qBittorrent.Cache = (() => {
};
};

const deepFreeze = (obj) => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#examples

const keys = Reflect.ownKeys(obj);
for (const key of keys) {
const value = obj[key];
if ((value && (typeof value === 'object')) || (typeof value === 'function'))
deepFreeze(value);
}
Object.freeze(obj);
};

class BuildInfoCache {
#m_store = {};

Expand All @@ -51,13 +63,15 @@ window.qBittorrent.Cache = (() => {
onSuccess: (responseJSON) => {
if (!responseJSON)
return;

deepFreeze(responseJSON);
this.#m_store = responseJSON;
}
}).send();
}

get() {
return structuredClone(this.#m_store);
return this.#m_store;
}
}

Expand All @@ -80,7 +94,9 @@ window.qBittorrent.Cache = (() => {
onSuccess: (responseJSON, responseText) => {
if (!responseJSON)
return;
this.#m_store = structuredClone(responseJSON);

deepFreeze(responseJSON);
this.#m_store = responseJSON;

if (typeof obj.onSuccess === 'function')
obj.onSuccess(responseJSON, responseText);
Expand All @@ -89,7 +105,7 @@ window.qBittorrent.Cache = (() => {
}

get() {
return structuredClone(this.#m_store);
return this.#m_store;
}

// obj: {
Expand All @@ -114,13 +130,15 @@ window.qBittorrent.Cache = (() => {
obj.onFailure(xhr);
},
onSuccess: (responseText, responseXML) => {
this.#m_store = structuredClone(this.#m_store);
for (const key in obj.data) {
if (!Object.hasOwn(obj.data, key))
continue;

const value = obj.data[key];
this.#m_store[key] = value;
}
deepFreeze(this.#m_store);

if (typeof obj.onSuccess === 'function')
obj.onSuccess(responseText, responseXML);
Expand Down

0 comments on commit bb8a012

Please sign in to comment.