Skip to content

Commit bb8a012

Browse files
authored
Revise cache internals
Now cache initialization and `get()` is less costly to use and it shifts the weight to `set()`. PR qbittorrent#20430.
1 parent 63c9b63 commit bb8a012

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/webui/www/private/scripts/cache.js

+21-3
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,18 @@ window.qBittorrent.Cache = (() => {
4040
};
4141
};
4242

43+
const deepFreeze = (obj) => {
44+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#examples
45+
46+
const keys = Reflect.ownKeys(obj);
47+
for (const key of keys) {
48+
const value = obj[key];
49+
if ((value && (typeof value === 'object')) || (typeof value === 'function'))
50+
deepFreeze(value);
51+
}
52+
Object.freeze(obj);
53+
};
54+
4355
class BuildInfoCache {
4456
#m_store = {};
4557

@@ -51,13 +63,15 @@ window.qBittorrent.Cache = (() => {
5163
onSuccess: (responseJSON) => {
5264
if (!responseJSON)
5365
return;
66+
67+
deepFreeze(responseJSON);
5468
this.#m_store = responseJSON;
5569
}
5670
}).send();
5771
}
5872

5973
get() {
60-
return structuredClone(this.#m_store);
74+
return this.#m_store;
6175
}
6276
}
6377

@@ -80,7 +94,9 @@ window.qBittorrent.Cache = (() => {
8094
onSuccess: (responseJSON, responseText) => {
8195
if (!responseJSON)
8296
return;
83-
this.#m_store = structuredClone(responseJSON);
97+
98+
deepFreeze(responseJSON);
99+
this.#m_store = responseJSON;
84100

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

91107
get() {
92-
return structuredClone(this.#m_store);
108+
return this.#m_store;
93109
}
94110

95111
// obj: {
@@ -114,13 +130,15 @@ window.qBittorrent.Cache = (() => {
114130
obj.onFailure(xhr);
115131
},
116132
onSuccess: (responseText, responseXML) => {
133+
this.#m_store = structuredClone(this.#m_store);
117134
for (const key in obj.data) {
118135
if (!Object.hasOwn(obj.data, key))
119136
continue;
120137

121138
const value = obj.data[key];
122139
this.#m_store[key] = value;
123140
}
141+
deepFreeze(this.#m_store);
124142

125143
if (typeof obj.onSuccess === 'function')
126144
obj.onSuccess(responseText, responseXML);

0 commit comments

Comments
 (0)