C# 三種字節數組(byte[])拼接的性能對比測試


之前做的通信框架,一直用的List<byte>做的數據接收池。今天有點閑暇時間,特地寫了個DEMO將C#中的三種字節數組拼接方式的性能做了一個對比測試。

代碼如下(若代碼有不嚴謹或錯誤之處,懇請指出。):

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);
        }
    }
}

  

 

測試結果:


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM