Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions src/color/p5.Color.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const toHexComponent = (v) => {
}

const serializationMap = new Map();
const srgbCoordsCache = new Map();



Expand Down Expand Up @@ -718,30 +719,38 @@ class Color {
}

_getRGBA(maxes=[1, 1, 1, 1]) {
// Get colorjs maxes
const colorjsMaxes = Color.#colorjsMaxes[RGB];
const key = `${this._color.space.id}-${this._color.coords.join(',')}-${this._color.alpha}`;
let srgbCoords = srgbCoordsCache.get(key);

if (srgbCoords === undefined) {
if (this.mode === RGB || this._color.space.id === 'srgb') {
srgbCoords = [...this._color.coords, this._color.alpha];
} else {
srgbCoords = [...to(this._color, 'srgb').coords, this._color.alpha];
}

// Normalize everything to 0,1 or the provided range (map)
let coords = structuredClone(to(this._color, 'srgb').coords);
coords.push(this._color.alpha);
if (srgbCoordsCache.size > 1000) {
srgbCoordsCache.delete(srgbCoordsCache.keys().next().value);
}
Comment on lines +732 to +734

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to have this. I wonder if 1000 is the right number? What would a typical number of colors set() would manipulate and what would be a sensible upper bound without it leaking memory?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typical sketches use far fewer than 1000 unique colors. However, image processing or complex generative art could exceed this. Each entry is small (~32 bytes), so 1000 entries ≈ 32KB max. I chose 1000 as a conservative default that covers most cases without significant memory impact. Would you prefer a different value or should we make it configurable?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can keep it as 1000 for now if the above benchmark still holds.

srgbCoordsCache.set(key, srgbCoords);
}

const rangeMaxes = maxes.map((v) => {
const colorjsMaxes = Color.#colorjsMaxes[RGB];
const rangeMaxes = maxes.map(v => {
if(!Array.isArray(v)){
return [0, v];
}else{
return v;
}
});

coords = coords.map((coord, i) => {
return srgbCoords.map((coord, i) => {
return map(
coord,
colorjsMaxes[i][0], colorjsMaxes[i][1],
rangeMaxes[i][0], rangeMaxes[i][1]
);
});

return coords;
}

_getMode() {
Expand Down
Loading