Golang Pointer Garbage Collection – Memory Management

Golang Garbage Collection

Garbage Collection means that you don’t have to take care of the deallocated memory. In Golang, memory is automatically reclaimed when it is not in use. Golang uses Pointer Garbage Collection and we don’t have to free up the allocated memory.

If you come from a high-level language background like Java, Python, Ruby, C#, etc, then you might know it already or never paid attention to this feature of the new programming languages.

Those who come from low-language background this feature will be a luxury for them.

The Garbage Collection feature in Golang is equivalent to C’s free() or C++’s delete for Pointers.

Garbage Collection makes it easy for us by deallocating memory but sometimes it is also possible to leak objects. This happens when you accidentally keep referencing the object when you have stopped using it.

When Golang Pointer Garbage Collection Comes in Use?

While writing a single-threaded Golang code, garbage collection is a luxury. But this changes when you start coding multi-threaded Golang code.

Example – Sharing pointers to an object between multiple threads, and later deleting the object makes it really hard. Referencing a thread for counting is also hard.

Golang Memory Management

Like Java, and unlike C or C++, Golang does not explicitly differentiate between stack and heap allocations. Memory is just a memory for Golang.

In Golang, If you create an object in Golang with local scope, then-current implementation of the object will be allocated on the stack unless it has its address taken somewhere in the memory.

Read Introduction to Golang to understand How and Why Golang is developed.

Read More About Golang Pointer Garbage Collection from Official Golang Page.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *