Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Unity and C# :Memory Management and Garbage Collection

4.00/5 (4 votes)
2 Jan 2014CPOL3 min read 20.5K  
Memory management is the art and the process of coordinating and controlling the use of memory in a computer system.

Memory management is the art and the process of coordinating and controlling the use of memory in a computer system.

Memory management can be divided into three areas:

  1. Memory management hardware (MMUs, RAM, etc.);

  2. Operating system memory management (virtual memory, protection);

  3. Application memory management (allocation, deallocation, garbage collection).

    -MemoryManagement.org

Unity Supports automatic memory management,where you don’t have to bother about your used assets/objects,Unity’s mono engine will release the memory and will use the same for other purposes.In the past,the user has to manually allocate the memory and release it at an appropriate time,which was an overhead.

Even now you can manually remove GameObjects or components of GameObjects at runtime  using Destroy Function.

using UnityEngine;
using System.Collections;

public class DestroyBasic : MonoBehaviour
{
  float timeDelay=3;
  void Update ()
 {
  if(Input.GetKey(KeyCode.Space))
   {

     //Under UnityEngine Namespace
     Destroy(gameObject);
    //With Time Delay
    Destroy(gameObject,timeDelay);
  }
 }
}

DestroyComponent

using UnityEngine;

using System.Collections;

public class DestroyComponent : MonoBehaviour
 {
 void Update ()
 {
  if(Input.GetKey(KeyCode.Space))
  {
   Destroy(GetComponent<MeshRenderer>());
  }
 }
}

Destroy is fine…How about DestroyImmediate? Which one to use?

DestroyImmediate

Destroys the object obj immediately. You are strongly recommended to use Destroy instead.

This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame). Use this function with care since it can destroy assets permanently! Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general programming practice, not just in Unity).

Value and Reference Types

  • Value types are types which hold both data and memory on the same location.
  • Memory allocated on stack.
    • These include integers, floats, booleans and Unity’s struct types (eg, Color andVector3).
  • A reference type has a pointer which points to the memory location.
  • Memory allocated on heap.
    • Examples of reference types include objects, strings and arrays.

When a function is called, the values of its parameters are copied to an area of memory reserved for that specific call. Data types that occupy only a few bytes can be copied very quickly and easily. However, it is common for objects, strings and arrays to be much larger and it would be very inefficient if these types of data were copied on a regular basis. Fortunately, this is not necessary; the actual storage space for a large item is allocated from the heap and a small “pointer” value is used to remember its location. From then on, only the pointer need be copied during parameter passing. As long as the runtime system can locate the item identified by the pointer, a single copy of the data can be used as often as necessary.

Garbage Collection

To determine which heap blocks are no longer in use, the memory manager searches through all currently active reference variables and marks the blocks they refer to as “live”. At the end of the search, any space between the live blocks is considered empty by the memory manager and can be used for subsequent allocations. For obvious reasons, the process of locating and freeing up unused memory is known as garbage collection (or GC for short).

Further reading on Automatic Memory Management :  http://bit.ly/1gRja5l

I thought of writing about Memory management in unity through C#,but nothing can beat Wendelin Reich’s articles in Gamasutra about C# memory Management for unity.

There are three posts on C# memory management,

  • This first post discusses the fundamentals of memory management in the garbage-collected world of .NET and Mono. Author also discussed some common sources of memory leaks.
  • The second looks at tools for discovering memory leaks. The Unity Profiler is a formidable tool for this purpose, but it’s also expensive. Author therefore discussed .NET disassemblers and the Common Intermediate Language (CIL) to show you how you can discover memory leaks with free tools only.
  • The third post discusses C# object pooling. Again, the focus is on the specific needs that arise in Unity/C# development.

Courtesy :Unity3d and Gamasutra


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)