Unity中 使用c# 自定义的值类型作为dictionary的key需注意

在Unity中使用C#自定义的值类型作为Dictionary的键时,会遇到额外的20B GC开销,因为默认使用ObjectEqualityComparer,导致对象装箱。若增加额外字段,GC开销会进一步增加。解决方法包括:实现IEquatable接口以优化GetHashCode,或者自定义Comparer类并传入Dictionary构造函数,避免装箱操作,从而减少内存消耗。
摘要由CSDN通过智能技术生成
public struct DictStruct
{
	public int x;
	public DictStruct(int x)
	{
		this.x = x;
	}
}
public class Test : MonoBehaviour
{
	private void Update()
	{
		TestEnumDict();
	}
	private void TestStruct()
	{
		Dictionary<DictStruct, int> dict = new Dictionary<DictStruct, int>();
		dict.Add(new DictStruct(1), 1);
	}
}

这时有20B的GC,其中int=4字节,而在比较的时候因为ObjectEqualityComparer的GetHashCode调用的是object的GetHashCode,需要转换成object进行比较。

    internal class ObjectEqualityComparer<T>: EqualityComparer<T>
    {
        [Pure]
        public override bool Equals(T x, T y) {
            if (x != null) {
                if (y != null) return x.Equals(y);
                return false;
            }
            if (y != null) return false;
            retur
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值