feat: implement LRU caching for user colors and avatar metadata to optimize performance
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user