10/28/2022
In structure that may use hashcode in C# like Dictionary, C# chooses default EqualityComparer when the user does not specify.
For Value type Enum, C# uses ObjectEqualityComparer, which will box Enum into an object and call the object's hashcode and equality function.
Hence, unnecessary GCs are generated from boxing in hashcode-required functions like Dictionary.ContainsKey(); Dictionary.Add()
private void DictOperation()
{
if (!DummyDict.ContainsKey(MyEnum.DummyEnum))
{
DummyDict.Add(MyEnum.DummyEnum, 0);
}
if (!DummyDict.ContainsKey(MyEnum.NotDummyEnum))
{
DummyDict.Add(MyEnum.NotDummyEnum, 1);
}
DummyDict[MyEnum.DummyEnum] = DummyDict[MyEnum.NotDummyEnum];
}
As we understand the reason the GC is the default EqualityComparer, we can simply assign a comparator when constructing the dictionary, and convert the Enum value to the int value for comparison.
public class MyEnumComparer : IEqualityComparer<MyEnum>
{
public bool Equals(MyEnum x, MyEnum y)
{
return (int)x == (int)y;
}
public int GetHashCode(MyEnum obj)
{
return (int)obj;
}
}
The problem has been solved in the new C# version, I test in 2021.3.6f1 and it has been fixed, but Unity does use older C# versions, so be careful.