内存中的C#数组大于预期 [英] C# array in memory larger than expected

查看:71
本文介绍了内存中的C#数组大于预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#(和Visual Studio 2010),我定义了一个由5个布尔值组成的结构(仅此而已).然后,我创建了该结构的16515072元素的数组.奇怪的是,ANTS内存分析器显示此阵列占用了80 MB以上的内存.

Using C# (and Visual Studio 2010), I defined a struct of 5 bools (and nothing else). Then I created an array of 16515072 elements of that struct. Strangely, the ANTS Memory profiler shows that this array is occupying more than 80 MB of memory.

但是,如果完美地打包了位,那么它应该只占用约10 MB.即使将5个布尔值打包成一个字节(由我编码)(我希望如此),该数组也应该仅为〜16 MB.

However, if the bits where perfectly packed it should only occupy ~10 MB. Even if the 5 bools were packed into (encoded by) a single byte (which I would expect), the array should only be ~16 MB.

我如何改善数组的包装以减少其占用的内存?优化大型阵列的内存占用量时,是否有任何通用的最佳实践?

How can I improve the packing of the array in order to reduce the memory it occypies? Are there any general best-pactices when optimizing the memory footprint of large arrays?

推荐答案

您得到的结果是正确的:在C#.NET bool中没有 打包-每个占一个字节,因此总数为16515072 * 5 = 82MB.

The results that you get are correct: in C# .NET bools are not packed - each one occupies a single byte, so the total is 16515072*5=82MB.

如果要将布尔值打包为位,可以使用单个byte存储值,并对getter和setter进行位操作:

If you would like to pack the booleans into bits, you can use a single byte for storing the values, and use bit operations for your getters and setters:

private byte storage;
public bool Property1 {
    get {
        return (storage & 0x01) != 0;
    }
    set {
        if (value) {
            storage |= 0x01;
        } else {
            storage &= 0xFE;
        }
    }
}
public bool Property2 {
    get {
        return (storage & 0x02) != 0;
    }
    set {
        if (value) {
            storage |= 0x02;
        } else {
            storage &= 0xFD;
        }
    }
}
public bool Property3 {
    get {
        return (storage & 0x04) != 0;
    }
    set {
        if (value) {
            storage |= 0x04;
        } else {
            storage &= 0xFB;
        }
    }
}

继续使用2的幂来表示其余属性(0x080x100x20等)的位掩码.

Continue using powers of 2 for bit masks of the remaining properties - 0x08, 0x10, 0x20, and so on.

这篇关于内存中的C#数组大于预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆