BitMap利用byte特性 针对排序+去重 最佳实践: 100万条数据的排序+去重用时200毫秒左右

static void Main(string[] args) { int[] data = new int[10000000]; /*alias*/ Random r = new Random(); for (int i = 0; i < data.Length; i++) { data[i] = r.Next(1, 10000000); } Stopwatch stop = new Stopwatch(); stop.Start(); List<byte> lstbyte = new List<byte>(); foreach (var item in data) { int unit = item / 8; int index = item % 8; if (lstbyte.Count <= unit) { lstbyte.AddRange(new byte[unit-lstbyte.Count + 1]); } lstbyte[unit] = set_bit(lstbyte[unit], index + 1, true); } List<int> result = new List<int>(); for (int i = 0; i < lstbyte.Count; i++) { int currentIndex = i*8; List<int> lstint = new List<int>(); if (lstbyte[i] > 0) { /** * 这段代码用于判断,byte对应位置的值是否有1 * 例如: 目标 byte:0010 0001 * 0010 0001 & 0000 0001 结果为1则 第一位为1 * 第二位比较方式就是目标byte和 0010 0001 & 0000 0010 * 为避免频繁的装箱拆箱操作,这里不用通过 Math.Pow计算平2的平方立方来得到目标比较数。 */ int b = lstbyte[i] & 0x01; if (b == 1) { lstint.Add(currentIndex+0); } b = lstbyte[i] & 0x02; if (b == 2) { lstint.Add(currentIndex + 1); } b = lstbyte[i] & 0x04; if (b == 4) { lstint.Add(currentIndex + 2); } b = lstbyte[i] & 0x08; if (b == 8) { lstint.Add(currentIndex + 3); } b = lstbyte[i] & 0x10; if (b == 16) { lstint.Add(currentIndex + 4); } b = lstbyte[i] & 0x20; if (b == 32) { lstint.Add(currentIndex + 5); } b = lstbyte[i] & 0x40; if (b == 64) { lstint.Add(currentIndex + 6); } b = lstbyte[i] & 0x80; if (b == 128) { lstint.Add(currentIndex + 7); } } result.AddRange(lstint); } stop.Stop(); Console.WriteLine("结果数:"+result.Count); //foreach (var item in result) //{ // Console.WriteLine(item); //} Console.WriteLine(string.Concat("时间:" ,stop.ElapsedMilliseconds ,"毫秒")); Console.ReadKey(); } /// <summary> /// 设置某一位的值 /// </summary> /// <param name="data"></param> /// <param name="index">要设置的位, 值从低到高为 1-8</param> /// <param name="flag">要设置的值 true / false</param> /// <returns></returns> static byte set_bit(byte data, int index, bool flag) { if (index > 8 || index < 1) throw new ArgumentOutOfRangeException(); int v = index < 2 ? index : (2 << (index - 2)); return flag ? (byte)(data | v) : (byte)(data & ~v); }
运行速度和待排序去重的最大数的大小有关系