首頁>技術>

緩衝區 是記憶體中的一組位元組序列,緩衝 是用來處理落在記憶體中的資料,.NET 緩衝 指的是處理 非託管記憶體 中的資料,用 byte[] 來表示。

Buffer 下的方法列表

Buffer 類包含了下面幾個方法:

BlockCopy(Array, Int32, Array, Int32)

用於將指定位置開始的 原陣列 copy 到 指定位置開始的 目標陣列。

ByteLength(Array)

表示陣列中 byte 位元組的總數。

GetByte(Array, Int32)

在陣列一個指定位置中提取出一個 byte。

SetByte(Array, Int32, Byte)

在陣列的一個指定位置中設定一個 byte。

MemoryCopy(Void, Void, Int64, Int64)

從第一個源地址上copy 若干個byte 到 目標地址中。

理解 Array 和 Buffer

在瞭解 Buffer 之前,我們先看看 Array 類,Array 類中有一個 Copy() 方法用於將陣列的內容 copy 到另一個數組中,在 Buffer 中也提供了一個類似的 BlockCopy() 方法和 Array.Copy() 做的一樣的事情,不過 Buffer.BlockCopy() 要比 Array.Copy() 的效能高得多,原因在於前者是按照 byte 複製,後者是 content 複製。

陣列之間的 bytes copy

你可以利用 Buffer.BlockCopy() 方法 將源陣列的位元組 copy 到目標陣列,如下程式碼所示:

static void Main(){  short [] arr1 = new short[] { 1, 2, 3, 4, 5};  short [] arr2 = new short[10];  int sourceOffset = 0;  int destinationOffset = 0;  int count = 2 * sizeof(short);  Buffer.BlockCopy(arr1, sourceOffset, arr2, destinationOffset, count);  for (int i = 0; i < arr2.Length; i++)  {      Console.WriteLine(arr2[i]);  }  Console.ReadKey();}

如果沒看懂上面輸出,我稍微解釋下吧,請看這句: int count = 2 * sizeof(short) 表示從 arr1 中 copy 4個位元組到 arr2 中,而 4 byte = 2 short,也就是將 arr1 中的 {1,2} copy 到 arr2 中,對吧。

理解陣列中位元組總長度

要想獲取陣列中的位元組總長度,可以利用 Buffer 中的 ByteLength 方法,如下程式碼所示:

static void Main(){  short [] arr1 = new short[] { 1, 2, 3, 4, 5};  short [] arr2 = new short[10];  Console.WriteLine("The length of the arr1 is: {0}",  Buffer.ByteLength(arr1));  Console.WriteLine("The length of the arr2 is: {0}",  Buffer.ByteLength(arr2));  Console.ReadKey();}

從圖中可以看出,一個 short 表示 2 個 byte, 5個 short 就是 10 個 byte,對吧,結果就是 short [].length * 2,所以 Console 中的 10 和 20 就不難理解了,接下來看下 Buffer 的 SetByte 和 GetByte 方法,他們可用於單獨設定和提取陣列中某一個位置的 byte,下面的程式碼展示瞭如何使用 SetByte 和 GetByte。

        static void Main()        {            short[] arr1 = { 5, 25 };            int length = Buffer.ByteLength(arr1);            Console.WriteLine("\nThe original array is as follows:-");            for (int i = 0; i < length; i++)            {                byte b = Buffer.GetByte(arr1, i);                Console.WriteLine(b);            }            Buffer.SetByte(arr1, 0, 100);            Buffer.SetByte(arr1, 1, 100);            Console.WriteLine("\nThe modified array is as follows:-");            for (int i = 0; i < Buffer.ByteLength(arr1); i++)            {                byte b = Buffer.GetByte(arr1, i);                Console.WriteLine(b);            }            Console.ReadKey();        }

Buffer 在處理 含有基元型別的一個記憶體塊上 具有超高的處理效能,當你需要處理記憶體中的資料 或者 希望快速的訪問記憶體中的資料,這時候 Buffer 將是一個非常好的選擇。

20
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • leetcode1680_go_連線連續二進位制數字