标签:style blog color os io strong for ar
因为项目需要合并几十K长的数组,本着效率出发,测试了一下各种方法。
我只找到了:
CopyTo 方式
Array.Copy 方式
BlockCopy 方式
MemoryStream 方式
Concat 方式
这几种方法,还有for循环一个个复制,想想也没有啥效率,因为还会多一个加法运算ByteAll(byte2.Length+k)=byte1(k),耗时是copyTo方式的13倍,虽然如此也比Concat方式要快一倍。
测试结果是copyTo,Array.Copy,BlockCopy三种方法基本上差不多,可以随便用,不过BlockCopy稍领先,上代码:
1 private void test() 2 { 3 Stopwatch watch = new Stopwatch(); 4 byte[] byte2 = new byte[15]; 5 FileStream fs = new FileStream("z:\\3.bmp", FileMode.Open); 6 byte[] byte1 = new byte[Convert.ToInt32(fs.Length - 1)] {}; 7 fs.Read(byte1, 0, byte1.Length); 8 fs.Close(); 9 10 11 watch.Reset(); 12 watch.Start(); 13 for (int i = 0; i <= 1000; i++) { 14 byte[] ByteAll = new byte[byte2.Length + byte1.Length - 1]; 15 byte2.CopyTo(ByteAll, 0); 16 byte1.CopyTo(ByteAll, byte2.Length); 17 } 18 watch.Stop(); 19 Console.WriteLine("CopyTo模式 耗时:" + watch.ElapsedTicks.ToString()); 20 21 22 watch.Reset(); 23 watch.Start(); 24 for (int i = 0; i <= 1000; i++) { 25 byte[] ByteAll = new byte[byte2.Length + byte1.Length - 1]; 26 Array.Copy(byte2, 0, ByteAll, 0, byte2.Length); 27 Array.Copy(byte1, 0, ByteAll, byte2.Length, byte1.Length); 28 } 29 watch.Stop(); 30 Console.WriteLine("Array.Copy模式 耗时:" + watch.ElapsedTicks.ToString()); 31 32 33 watch.Reset(); 34 watch.Start(); 35 for (int i = 0; i <= 1000; i++) { 36 byte[] ByteAll = new byte[byte2.Length + byte1.Length - 1]; 37 Buffer.BlockCopy(byte2, 0, ByteAll, 0, byte2.Length); 38 Buffer.BlockCopy(byte1, 0, ByteAll, byte2.Length, byte1.Length); 39 } 40 watch.Stop(); 41 Console.WriteLine("BlockCopy模式 耗时:" + watch.ElapsedTicks.ToString()); 42 43 44 watch.Reset(); 45 watch.Start(); 46 for (int i = 0; i <= 1000; i++) { 47 byte[] ByteAll = new byte[byte2.Length + byte1.Length - 1]; 48 Stream s = new MemoryStream(); 49 s.Write(byte1, 0, byte1.Length); 50 s.Write(byte2, 0, byte2.Length); 51 s.Position = 0; 52 s.Read(ByteAll, 0, ByteAll.Length); 53 s.Close(); 54 } 55 watch.Stop(); 56 Console.WriteLine("MemoryStream模式 耗时:" + watch.ElapsedTicks.ToString()); 57 58 59 watch.Reset(); 60 watch.Start(); 61 for (int i = 0; i <= 1000; i++) { 62 byte[] ByteAll = byte2.Concat(byte1).ToArray; 63 } 64 watch.Stop(); 65 Console.WriteLine("Concat模式 耗时:" + watch.ElapsedTicks.ToString()); 66 67 }
测试结果是:
CopyTo模式 耗时:194105
Array.Copy模式 耗时:192310
BlockCopy模式 耗时:190375
MemoryStream模式 耗时:755342
Concat模式 耗时:8702930
我尝试用Array.Resize(byte2, byte1.Length + byte2.Length)来直接把byte2扩大,结果测试发现还不如新建一个ByteAll来得快.
标签:style blog color os io strong for ar
原文地址:http://www.cnblogs.com/qianyin/p/3907304.html