C# 三种字节数组(byte[])拼接的性能对比测试
之前做的通信框架,一直用的List<byte>做的数据接收池。今天有点闲暇时间,特地写了个DEMO将C#中的三种字节数组拼接方式的性能做了一个对比测试。
代码如下(若代码有不严谨或错误之处,恳请指出。):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace BytesLinkDemo { class Program { static int RunCount = 10000; static void Main( string [] args) { ArrayCopyTest(); BlockCopyTest(); ListTest(); Console.ReadKey(); } static void ListTest() { List< byte > byteSource = new List< byte >(); byteSource.Add(11); Stopwatch sw = new Stopwatch(); sw.Start(); for ( int i = 0; i < RunCount; i++) { byte [] newData = new byte [10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; byteSource.AddRange(newData); } byte [] data = byteSource.ToArray(); //byte[] subData = byteSource.Take(100).ToArray();//获取前100个字节 //byteSource.RemoveRange(0, 100);//取出后删除 //byteSource.GetRange(100, 100);//从下标100开始取100个字节 sw.Stop(); Console.WriteLine( "ListTest " + sw.ElapsedMilliseconds + " 毫秒,数组长度:" + data.Length); } static void ArrayCopyTest() { byte [] byteSource = new byte [1] { 11 }; Stopwatch sw = new Stopwatch(); sw.Start(); for ( int i = 0; i < RunCount; i++) { byte [] newData = new byte [10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; byte [] tmp = new byte [byteSource.Length + newData.Length]; Array.Copy(byteSource, tmp, byteSource.Length); Array.Copy(newData, 0, tmp, byteSource.Length, newData.Length); byteSource = tmp; } sw.Stop(); Console.WriteLine( "ArrayCopyTest " + sw.ElapsedMilliseconds + " 毫秒,数组长度:" + byteSource.Length); } static void BlockCopyTest() { byte [] byteSource = new byte [1] { 11 }; Stopwatch sw = new Stopwatch(); sw.Start(); for ( int i = 0; i < RunCount; i++) { byte [] newData = new byte [10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; byte [] tmp = new byte [byteSource.Length + newData.Length]; System.Buffer.BlockCopy(byteSource, 0, tmp, 0, byteSource.Length); System.Buffer.BlockCopy(newData, 0, tmp, byteSource.Length, newData.Length); byteSource = tmp; } sw.Stop(); Console.WriteLine( "BlockCopyTest " + sw.ElapsedMilliseconds + " 毫秒,数组长度:" + byteSource.Length); } } } |
测试结果:
无人机技术交流QQ群:951349285,mavlink,missionplanner,qgroundcontrol,PX4,ArduPilot。
JAVA&NET技术,跳槽,软考交流QQ群:456257217,有问题的可以在群里面提问交流。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)