Search⌘ K
AI Features

Solution: Memory Handling

Explore how to optimize memory handling in Go by using the make function with proper slice capacity. Understand techniques to reduce memory usage by copying needed data and preventing garbage collection issues in collection types.

We'll cover the following...
...
Go (1.16.5)
package main
import (
"runtime"
"testing"
)
const megabyte = 1024 * 1024
func TestAllocations(t *testing.T) {
count := 10
arr := make([][]int, count)
for i := 0; i < count; i++ {
newarr := make([]int, 0, megabyte)
for k := 0; k < megabyte; k++ {
newarr = append(newarr, k)
}
arr2 := make([]int, 2)
copy(arr2, newarr[0:2])
arr[i] = arr2
}
// for test purposes, run garbage collector to clean up unused memory
runtime.GC()
// check how much memory this program is still using
var m runtime.MemStats
runtime.ReadMemStats(&m)
if m.Alloc/megabyte >= 1 {
t.Error("there is too much memory allocated")
}
// check if the array has expected data
for i, a := range arr {
if len(a) != 2 || a[0] != 0 || a[1] != 1 {
t.Errorf("Array item #%v does not have valid data", i)
}
}
}
...