且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将结构转换为无副本的字节数组?

更新时间:2023-11-15 20:10:58

由于数组很大,这实际上是您可以执行所需操作的唯一方法:

Since you have a big array, this is really the only way you will be able to do what you want:

var myBigArray = new Byte[100000];

// ...

var offset = 0;
var hash = sha256.ComputeHash(pkBytes);
Buffer.BlockCopy(myBigArray, offset, hash, 0, hash.Length);

// if you are in a loop, do something like this
offset += hash.Length;

此代码非常有效,即使是在紧密的循环中, ComputeHash 的结果也将被收集到快速的Gen0集合中,而 myBigArray 将在Large对象堆,且未移动或收集. Buffer.BlockCopy 在运行时进行了高度优化,即使在固定目标并使用展开的指针副本的情况下,也可以提供您可能实现的最快副本.

This code is very efficient, and even in a tight loop, the results of ComputeHash will be collected in a quick Gen0 collection, while myBigArray will be on the Large Object Heap, and not moved or collected. The Buffer.BlockCopy is highly optimized in the runtime, yielding the fastest copy you could probably achieve, even in the face of pinning the target, and using an unrolled pointer copy.