Golang 101 : Looking at how Garbage Collector works

Golang 101 : Looking at how Garbage Collector works

Take a look at GC running visually

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
}

‌Understanding the code

There is a package in Golang standard library called runtimewhich contains alot of useful function like :

  • runtime.ReadMemStats(&mem)
  • runtime.GC()

garbage-collector benchmark golang

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Golang Web Development:Th Best Programming Language in 2020

Golang Web Development is the new trend globally. Get all the details about the Golang development here. Hire Golang Developers.

How Benchmarking Your Code Will Improve Your Ruby Skills

Learning to code is a path full of struggles, and learning Ruby isn't the exception. But you'll agree with me, that practice is the best way to learn and develop your skills.

A Deep Dive Into Benchmarking in Golang

A deep dive into benchmarking in Golang. Go lets us developers benchmark using the testing package. In this article, I want to dive deeper into benchmarks in Golang, but I’ll start from scratch.

What is a garbage collector?

The garbage collector (GC) is a part of the .NET framework which is initialized by the common language run-time (CLR) to manage the allocation and release of memory in an application.

Golang Array Example | Arrays in Go Tutorial Explained

Golang array is a fixed-size collection of items of the same type. The items of an array are stored sequentially and can be accessed using their index.