Middle
What is caching and why is it needed?
sobes.tech AI
Answer from AI
Caching is the process of storing the results of expensive operations (such as computations, database queries, or external service calls) in fast-access storage so that subsequent requests can use the already computed data instead of performing the operation again.
Why caching is needed:
- It speeds up the application by reducing response time.
- It reduces load on resources (DB, network, CPU).
- It increases system scalability.
In Go, caching is often implemented using built-in data structures (map) or specialized libraries, for example, for in-memory cache. Here's a simple example of a cache in Go:
package main
import (
"fmt"
"sync"
"time"
)
type Cache struct {
mu sync.Mutex
store map[string]string
}
func NewCache() *Cache {
return &Cache{store: make(map[string]string)}
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.store[key]
return val, ok
}
func (c *Cache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = value
}
func main() {
cache := NewCache()
cache.Set("time", time.Now().String())
if val, ok := cache.Get("time"); ok {
fmt.Println("Cached value:", val)
}
}