DEV Community

Discussion on: Garbage collection - explain it like im 5 request (language agnostic)

Collapse
 
g1ntas profile image
Gintas Kovalevskis • Edited

It's all about understanding how memory works.

Just as in physics we have weight units (grams), so in computing we have size units (bytes). Every file you download or every character you print it takes specific amount of your computer storage. It's basics you probably already know.

Now there are two types of storage in your computer: primary and secondary. Primary storage is usually known as memory or RAM and can be accessed directly by the processor, so it makes it fast, but trade off is it's low capacity.
Secondary storage is your hard drive, it's where all your files and applications are stored. Difference is that it can not be accessed directly by processor and thus needs first be loaded into Primary storage, which makes it significantly slower to operate on, on the other hand capacity is so large, that you don't really need to worry about it.

Now when you have a code, you have variables which contain data, the data have size and thus consumes storage. As amount of variables grow, also grow consumption of your memory, and when that consumption reaches a limit, application will crash, because there's nowhere to store that data anymore.

That's where garbage collection comes in, in short, it gets rid of variables that are not used anymore and so frees up a storage space, which can be used for other variables. Usually it works differently on different languages, but basic idea is to destroy variable whenever it's possible, for example at the end of the function (one of the reasons why it's a good idea to split code into smaller functions).