Golang 101: Looking at how Garbage Collector works

Quick Look at Garbage Collector

‌A simple program that creates a byte array of 100000000 elements and lets print the memory allocations.

package main
import (
"fmt"
"runtime"
"time"
)
func printStats(mem runtime.MemStats) {
runtime.ReadMemStats(&mem)
fmt.Println("mem.Alloc:", mem.Alloc)
fmt.Println("mem.TotalAlloc:", mem.TotalAlloc)
fmt.Println("mem.HeapAlloc:", mem.HeapAlloc)
fmt.Println("mem.NumGC:", mem.NumGC)
fmt.Println("-----")
}
func main() {
var mem runtime.MemStats
for i := 0; i < 2; i++ {
s := make([]byte, 100000000)
if s == nil {
fmt.Println("Operation failed!")
}
printStats(mem)
}
time.Sleep(time.Second)
// adding time.Sleep so that GC finishes it works and print out the output to terminal
}

Source: https://medium.com/dev-genius/golang-101-looking-at-how-garbage-collector-works-98392737a475

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 168

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply

two × two =

Physical Address

SHANKAR VIHAR, PLOT NO 1260, KHANDAGIRI, BHUBANESWAR-751030, Khordha, Odisha, India