Implement Cache Memory in Go

Aman Agarwal
2 min readApr 30, 2021

--

If we google about cache memory we will get,”Cache memory is an extremely fast memory type that acts as a buffer between RAM and the CPU. It holds frequently requested data and instructions so that they are immediately available to the CPU when needed. Cache memory is used to reduce the average time to access data from the Main memory ”.

So is it Important ?

Yes It is important because it improves the efficiency of data retrieval. It stores program instructions and data that are used repeatedly in the operation of programs or information that the CPU is likely to need next. … Fast access to these instructions increases the overall speed of the program.

In Go

we will be using Patrick Mylund Nielsen’s git repo of go-cache.

In Golang we store value/data in cache memory by key: value format. let’s go by some code!

type Example struct {
Name string
age int64
}
func main() {
// Create a cache with a default expiration time of 5 minutes, and which purges expired items every 10 minutes
newExample := &Example{
Name: "testName1",
age: 22,
}
c := cache.New(5*time.Minute, 10*time.Minute)
foo, found := c.Get("foo")
if found {
a := foo.([]Example)
a = append(a, *newExample)
c.Set("foo", a, cache.NoExpiration)
fmt.Println("stored from if part")
} else {
c.Set("foo", newExample, cache.NoExpiration)
fmt.Println("stored from else part")
}
foo, found = c.Get("foo")
if found {
fmt.Println(foo)
}
}

here above “foo” is the key and our Example structure is our value to be stored in a cache.

we initialized “ c ” with cache accessible, which generates a cache memory block of time as specified in respect of default expiration, cleanup interval both of time. Duration type.

Then everything is simple as it looks, to push data we use Set() and to pop data we use Get() which returns the data and the bool value for operation representation.

You can find its working example here.

--

--

Aman Agarwal

Engineer | Explorer | Blockchain | Golang | JavaScript developer