feat: implement LRU caching for user colors and avatar metadata to optimize performance

This commit is contained in:
2026-04-22 02:47:21 +10:00
parent d4cb0b7435
commit ec6fe77567
3 changed files with 125 additions and 11 deletions

View File

@@ -204,9 +204,52 @@ export function useUserColor(): [
return [color, updateColor, loading];
}
// Cache for user colors to avoid refetching for each message
const userColorCache = new Map<string, { color: string | undefined; timestamp: number }>();
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
/**
* LRU Cache implementation with max size limit
*/
class LRUCache<K, V> {
private cache: Map<K, V>;
private maxSize: number;
constructor(maxSize: number) {
this.cache = new Map();
this.maxSize = maxSize;
}
get(key: K): V | undefined {
const value = this.cache.get(key);
if (value !== undefined) {
// Move to end (most recently used)
this.cache.delete(key);
this.cache.set(key, value);
}
return value;
}
set(key: K, value: V): void {
// If key exists, delete it first to re-add at end
if (this.cache.has(key)) {
this.cache.delete(key);
}
// If at max size, remove oldest (first) entry
else if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
if (firstKey !== undefined) {
this.cache.delete(firstKey);
}
}
this.cache.set(key, value);
}
clear(): void {
this.cache.clear();
}
}
// LRU cache for user colors to avoid refetching for each message
const userColorCache = new LRUCache<string, { color: string | undefined; timestamp: number }>(100);
const CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
/**
* Hook to get another user's chosen profile color from their avatar metadata