git » sdk » commit a475b86

Cache computed colours

author Stephen Paul Weber
2025-10-03 02:44:20 UTC
committer Stephen Paul Weber
2025-10-03 02:44:20 UTC
parent b9b02631540ee8af1ee094a15ddfe92b20361c64

Cache computed colours

Hashing and colour space conversion can be CPU intensive if done a lot,
which they are when re-rendering a list of eg avatars.

borogove/Color.hx +10 -0

diff --git a/borogove/Color.hx b/borogove/Color.hx
index de894dc..c260493 100644
--- a/borogove/Color.hx
+++ b/borogove/Color.hx
@@ -6,7 +6,13 @@ import haxe.crypto.Sha1;
 import borogove.Util;
 
 class Color {
+	private static var cache: Map<String, String> = [];
+	private static var cacheSize = 0;
+
 	public static function forString(s:String) {
+		final fromCache = cache[s];
+		if (fromCache != null) return fromCache;
+
 		var hash = Sha1.make(bytesOfString(s));
 		var hue = (hash.getUInt16(0) / 65536.0) * 360;
 		var color = new Hsluv();
@@ -14,6 +20,10 @@ class Color {
 		color.hsluv_s = 100;
 		color.hsluv_l = 50;
 		color.hsluvToHex();
+		if (cacheSize < 2000) {
+			cache[s] = color.hex;
+			cacheSize++;
+		}
 		return color.hex;
 	}