Due to comparing enums causing boxing in lists.Contains, there is a lot of memory being allocated causing a lot of garbage collection.
Take this code for example
Click for code
using UnityEngine;
using System.Collections.Generic;
public class TestListGarbageCollection : MonoBehaviour
{
public enum Test {EnumList, EnumToIntList}
public Test test;
enum TestEnum {One, Two, Three}
List<TestEnum> enumList;
List<int> enumIntList;
public int loopAmount = 100;
void Start()
{
enumList = new List<TestEnum>() {TestEnum.One};
enumIntList = new List<int>() {(int)TestEnum.One};
}
void Update()
{
for(int i = 0; i < loopAmount; i++)
{
if(test == Test.EnumList) if(enumList.Contains(TestEnum.Two)){} //seems to allocate 40B per enum in the list that it checks over (probably due to boxing)
if(test == Test.EnumToIntList) if(enumIntList.Contains((int)TestEnum.Two)){} //seems to allocate nothing
}
}
}
When comparing enums in a list, for every enum in the list there will be a 40B memory allocation for each enum you compare. (doing “if(TestEnum.One == TestEnum.Two){}” causes no memory allocations)
However, if you cast the enums to ints, there seems to be no memory allocated.
The code above is causing garbage memory of about 4KB each frame since it is looping 100 times per frame.
This is only when there is 1 enum in the list. If there were 10 enums, it would be about 40KB per frame, while the int version still shows 0.
I am wondering how people are handling this? Its difficult to make any generic enum method or classes due to there being no enum constraint, so that seems to be out of the question.
Should I just do what I am doing here and always cast an int?
Any info is appreciated!