CodeBlanks Logo Icon CodeBlanks

Garbage collector

Learn how the C# GC works and the cost of allocation.

What is the garbage collector?

In a C# program the memory of objects that are no longer used is reclaimed automatically. The structure that does this is called the garbage collector (GC). When an object has no references left, the GC can clean it up.

Nesne kasa = new Nesne(); // allocation
kasa = null;              // no reference left
// the GC can clean this object

Thanks to the GC there is no need to free memory by hand.

The cost of allocation

Creating a new object means reserving memory, that is, an allocation. Every allocation raises the chance of the GC running, and small hiccups can happen at collection time. This is why producing new objects every frame is avoided.

void Update()
{
    // an allocation every frame raises GC pressure
    int[] dizi = new int[8];
}

A game with fewer allocations runs smoother.

Practice Keep an allocation counter

In a class named BellekTakibi, define a string field named islem with the value "Tahsis" and an integer field named nesneSayisi with the value 3. In the Start method increase nesneSayisi by two and print the text "Toplam nesne: " joined with nesneSayisi using Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class BellekTakibi : MonoBehaviour
{
    // islem adli metin alanini "Tahsis", nesneSayisi adli tam sayi alanini 3 degeriyle tanimla

    void Start()
    {
        // nesneSayisi degerini iki artir
        // "Toplam nesne: " + nesneSayisi biciminde yazdir
    }
}

Sample solution

Player.cs
using UnityEngine;

public class BellekTakibi : MonoBehaviour
{
    string islem = "Tahsis";
    int nesneSayisi = 3;

    void Start()
    {
        nesneSayisi = nesneSayisi + 2;
        Debug.Log("Toplam nesne: " + nesneSayisi);
    }
}

Expected output

Toplam nesne: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When can an object be cleaned by the GC?

  • Automatically in every frame
  • When the script is compiled
  • When the GameObject is added to the scene
  • When it has no references left Correct answer

Explanation: The GC only cleans objects that no longer have any references; it does not touch reachable objects.

2 Trigger a GC collection manually

Question
    System.____.Collect();
Answer
    System.GC.Collect();

Explanation: The GC class lives inside the System namespace; System.GC.Collect() can trigger a collection manually.

3 GC terms

Term Meaning
GC (Garbage Collector) The structure that reclaims memory
Tahsis Reserving memory for a new object
Summing The cleanup pass of the GC
Referans The link that points to an object

All lessons in Expert