Skip to content

Commit 854b6eb

Browse files
committed
Memoize color object serialization
Still not efficient enough as color object are frequently created and each will need to be serialized once regardless of how many times it is used.
1 parent cee5253 commit 854b6eb

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/color/p5.Color.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ import HSBSpace from './color_spaces/hsb.js';
3333
const map = (n, start1, stop1, start2, stop2) =>
3434
((n - start1) / (stop1 - start1) * (stop2 - start2) + start2);
3535

36+
const serializationMap = new WeakMap();
37+
3638
class Color {
3739
// Reference to underlying color object depending on implementation
3840
// Not meant to be used publicly unless the implementation is known for sure
@@ -242,10 +244,15 @@ class Color {
242244
* </div>
243245
*/
244246
toString(format) {
245-
// NOTE: memoize
246-
return serialize(this._color, {
247-
format
248-
});
247+
// NOTE: memoize more
248+
let colorString = serializationMap.get(this._color);
249+
if(!colorString){
250+
colorString = serialize(this._color, {
251+
format
252+
});
253+
serializationMap.set(this._color, colorString);
254+
}
255+
return colorString;
249256
}
250257

251258
/**

0 commit comments

Comments
 (0)