CodeBlanks Logo Icon CodeBlanks

Heap allocation

Learn the cost of heap allocation and how to avoid it.

Heap allocation

The heap is the dynamic memory region where objects are stored. Every object created with the new keyword sits on the heap, and this operation is called a heap allocation. A heap allocation costs more than putting a value on the stack.

GameObject kasa = new GameObject("Kasa"); // heap allocation

Large or frequent allocations increase memory pressure.

Avoiding allocations

The first way to avoid allocation cost is to reuse objects. Producing an object once and keeping it is much cheaper than creating a new one every frame. Unnecessary temporary objects should also be reduced.

private Nesne nesne; // produced once

void Start()
{
    nesne = new Nesne();
}

This way the allocation count drops and the GC runs less often.

Practice Compute the allocation cost

In a class named HeapTakip, define an integer field named tahsisMaliyeti with the value 10 and an integer field named toplamMaliyet with the value 0. In the Start method set toplamMaliyet to three times tahsisMaliyeti and print the text "Toplam maliyet: " joined with toplamMaliyet using Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class HeapTakip : MonoBehaviour
{
    // tahsisMaliyeti adli tam sayi alanini 10, toplamMaliyet adli tam sayi alanini 0 degeriyle tanimla

    void Start()
    {
        // toplamMaliyet degerini tahsisMaliyeti degerinin uc kati yap
        // "Toplam maliyet: " + toplamMaliyet biciminde yazdir
    }
}

Sample solution

Player.cs
using UnityEngine;

public class HeapTakip : MonoBehaviour
{
    int tahsisMaliyeti = 10;
    int toplamMaliyet = 0;

    void Start()
    {
        toplamMaliyet = tahsisMaliyeti * 3;
        Debug.Log("Toplam maliyet: " + toplamMaliyet);
    }
}

Expected output

Toplam maliyet: 30

Questions and answers

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

1 Which of the following causes a heap allocation?

Player.cs
GameObject kasa = new GameObject("Kasa");
  • Printing text with Debug.Log
  • Creating a new object with new Correct answer
  • Assigning a constant value to a variable
  • Calling a method

Explanation: The new keyword reserves a new object on the heap; the other operations alone do not allocate.

2 Create the new object with new

Question
    GameObject kasa = ____ GameObject("Kasa");
Answer
    GameObject kasa = new GameObject("Kasa");

Explanation: A heap allocation is done with the new keyword; this is how objects are created in C#.

3 Heap allocation terms

Term Meaning
Heap Dynamic memory storing objects
new anahtarı Performs a heap allocation
Tahsis maliyeti The memory cost of a new object
Yeniden kullanma The technique that reduces allocations

All lessons in Expert