C#位操作的内存占用和效率比较:bool数组、BitArray和byte数组

为了选择高效的位操作方式,对于bool数组、BitArray和byte数组进行了对比测试,试验方法如下:初始化一个含有214748364个元素的bool数组和BitArray。另外,构建能容纳那么多位的字节数组。进行位操作(方法读取里语句与直接操作的语句相同)。
试验结论如下:字节数组的直接操作是内存占用最小,速度最快发方法

对比项目 bool数组 bitArray 字节数组(A直接操作) 字节数组(B通过方法读取)
所有元素置位 639~748ms 2300ms 140ms 904ms
所有元素读取 764ms 2012ms 203ms 780ms
form1内存 215MB 27.253MB 25.6MB 25.6MB
        bool[] boolArray;
        byte[] byteArray;
        BitArray bitArray;
        private void button2_Click(object sender, EventArgs e)
        {            
            int a = Int32.MaxValue / 10;
            boolArray = new bool[a];
            byteArray = new byte[(int)(Math.Ceiling((double)a / 8))];
            bitArray = new BitArray(a);
            DateTime t1 = DateTime.Now;
            bool b1;
            for (int i = 0; i < a; i++)
            {
                b1 = boolArray[i];
            }
            DateTime t2 = DateTime.Now;
            for (int i = 0; i < a; i++)
            {
                b1 = bitArray[i];
            }
            DateTime t3 = DateTime.Now;
            byte b = 0;
            int i1 = a / 8;
            int f = 0;
            int result;
            byte btemp;
            for (int i = 0; i < i1; i += 8)
            {
                for (int j = 0; j < 8; j++)
                {
                    
                    //B 通过函数读取
                    result = tagHelp.GetbitValueFromByte(byteArray[f], j);
                    //A 通过语句1直接读取
                    //btemp = (byte)(byteArray[f] >> j & 1);

                    //B 通过函数进行设置位
                    //byteArray[f] = tagHelp.setBitForByte(byteArray[f], j, true);
                    //A 通过语句进行设置
                    //if (true)
                    //{
                    //    byteArray[f] |= (byte)(0x1 << j);
                    //}

                    //内部无语句时的时间为46ms。
                }
                f++;
            }
            DateTime t4 = DateTime.Now;
            double ta = (t2 - t1).TotalMilliseconds;
            double tb = (t3 - t2).TotalMilliseconds;
            double tc = (t4 - t3).TotalMilliseconds;

            boolArray = null;
            bitArray = null;
        }

2020年4月30日

猜你喜欢

转载自blog.csdn.net/chengjl8/article/details/105869505