缓冲区
是内存中的一组字节序列,缓冲
是用来处理落在内存中的数据,.NET 缓冲
指的是处理 非托管内存
中的数据,用 byte[]
来表示。html
当你想把数据写入到内存或者你想处理非托管内存中的数据,可使用 .NET 提供的 System.Buffer
类,这篇文章就来讨论如何使用 Buffer。git
Buffer 类包含了下面几个方法:github
用于将指定位置开始的 原数组 copy 到 指定位置开始的 目标数组。segmentfault
表示数组中 byte 字节的总数。数组
在数组一个指定位置中提取出一个 byte。性能
在数组的一个指定位置中设置一个 byte。url
从第一个源地址上copy 若干个byte 到 目标地址中。spa
在了解 Buffer 以前,咱们先看看 Array 类,Array 类中有一个 Copy()
方法用于将数组的内容 copy 到另外一个数组中,在 Buffer 中也提供了一个相似的 BlockCopy()
方法和 Array.Copy()
作的同样的事情,不过 Buffer.BlockCopy()
要比 Array.Copy()
的性能高得多,缘由在于前者是按照 byte 拷贝,后者是 content 拷贝。code
你能够利用 Buffer.BlockCopy()
方法 将源数组的字节 copy 到目标数组,以下代码所示:htm
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 将是一个很是好的选择。
译文连接: https://www.infoworld.com/art...
更多高质量干货:参见个人 GitHub: csharptranslate