为什么包含自定义结构实际上增加了我的c#类的大小?

时间:2015-12-30 16:31:08

标签: c# memory struct

我有一个有几个花车的课程,以及其他几个领域......

 public class tResult
    {
    public byte Days;
    public int UpCount;
    public int DownCount;
    public int SameCount;
    public float UpRatio;
    public float DownRatio;
    public float SameRatio;
    public float UpAverage;
    public float DownAverage;
    public float Average;
    public float OccurancesCF;
    public float DirectionCF;
    }

使用Float代替Percentage,我的类每个需要88个字节(使用Jon Skeet的测试在GC.GetTotalMemory(true)次调用之间创建1M实例)。

当我用floats类(2个字节的数据)替换5个percentage(4个字节)时,我的大小增加到96个字节。

public struct Percentage : IComparable
{
    public Int16 Hundredths;
    public Percentage(double X) { Hundredths = (Int16)(X * 100); }
    public double Ratio { get { return Hundredths / 100.0; } set { Hundredths = (Int16)(value * 100); } }
    public override string ToString() => (Hundredths / 100.0).ToString("##0.00");
    public int CompareTo(object obj) => Hundredths.CompareTo(((Percentage)obj).Hundredths);
}

    public class tResult
    {
            public byte Days;
            public int UpCount;
            public int DownCount;
            public int SameCount;
            public Percentage UpRatio;
            public Percentage DownRatio;
            public Percentage SameRatio;
            public float UpAverage;
            public float DownAverage;
            public float Average;
            public Percentage OccurancesCF;
            public Percentage DirectionCF;
    }

我的问题是为什么它上升而不是下降?我在这里读到的所有东西(包括Jon和Eric Lippert的帖子)让我觉得它们应该按大小重新排序,因此应该减少大约10个字节。

0 个答案:

没有答案