使用私有类代替字段性能/内存损失

本文关键字:性能 字段 内存 损失 | 更新日期: 2023-09-27 18:17:39

我在审查某人的代码时遇到了这个私有类:

class CustomType : Dictionary<int, SomeOtherCustomType>
{
    // This is empty; nothing omitted here
}
然后在整个父类中使用

CustomType。这当然很简洁,因为CustomType比

Dictionary<int, SomeOtherCustomType>

我的问题是,有一个内部类只是为了一个快捷方式的性能/内存的含义是什么?在对性能敏感的应用程序中,这会导致更高的内存和/或CPU使用率吗?

使用私有类代替字段性能/内存损失

除非有其他原因需要定义自定义类型,否则我建议将其改为using语句。

using CustomType = Dictionary<int, SomeOtherCustomType>;

它只是为字典定义了一个别名,如果你正在使用一些复杂的参数化类,它会非常有用。

这消除了声明新类型的需要,因为就目前的代码而言,下面的操作将失败。

CustomType dictionary = new Dictionary<int, SomeOtherCustomType>(); //custom type is a different class and can't be instantiated with a dictionary

它的长短是,no。类CustomType根据定义是一个Dictionary<int, SomeOtherCustomType>,因此它将被这样分配。