It seems like Unity never returns any OS memory when doing a GC. I have attached some code to verify this. If you allocate a lot of memory you will see the heap size grow, but then doing a full gc, it never reduces, only the used portion decreases. This would seem to indicate that once Unity allocates memory from the OS, it never returns it. Is this true?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CreateGiantHeapThenDestroy : MonoBehaviour {
private List<byte[]> byteArrayList = new List<byte[]>();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
uint heapsize = Profiler.GetMonoHeapSize();
uint usedmonosize = Profiler.GetMonoUsedSize();
uint reserved = Profiler.GetTotalReservedMemory();
uint unusedreserved = Profiler.GetTotalUnusedReservedMemory();
GUILayout.Label(string.Format("Heapsize: {0}",heapsize/(1024*1024)));
GUILayout.Label(string.Format("Usedsize: {0}",usedmonosize/(1024*1024)));
GUILayout.Label (string.Format ("Reserved: {0}",reserved/(1024*1024)));
GUILayout.Label (string.Format ("UnusedReserved: {0}",unusedreserved/(1024*1024)));
if(GUILayout.Button ("Run GC")) {
System.GC.Collect(1000,System.GCCollectionMode.Forced);
}
if(GUILayout.Button("Allocate 100MB Memory")) {
byteArrayList.Add (new byte[1024*1024*100]);
}
if(byteArrayList.Count>0) {
if(GUILayout.Button("Free 100MB Memory")) {
byteArrayList.RemoveAt(byteArrayList.Count-1);
}
if(GUILayout.Button ("Free All Memory")) {
byteArrayList.Clear();
}
}
}
}