getCached retrieves a cached result or computes and caches it.
(key cacheKey, compute func() string)
| 31 | |
| 32 | // getCached retrieves a cached result or computes and caches it. |
| 33 | func (c *stringCache) getCached(key cacheKey, compute func() string) string { |
| 34 | // Fast path: read lock for cache hit |
| 35 | c.mu.RLock() |
| 36 | if result, ok := c.cache[key]; ok { |
| 37 | c.mu.RUnlock() |
| 38 | return result |
| 39 | } |
| 40 | c.mu.RUnlock() |
| 41 | |
| 42 | // Slow path: compute and cache |
| 43 | c.mu.Lock() |
| 44 | defer c.mu.Unlock() |
| 45 | |
| 46 | // Double-check in case another goroutine computed it |
| 47 | if result, ok := c.cache[key]; ok { |
| 48 | return result |
| 49 | } |
| 50 | |
| 51 | result := compute() |
| 52 | c.cache[key] = result |
| 53 | return result |
| 54 | } |