Jan*_*oom 3 c# performance unmanaged
我有一个数组,说:
var arr1 = new [] { 1, 2, 3, 4, 5, 6 };
Run Code Online (Sandbox Code Playgroud)
现在,当我的数组大小超过5时,我想将当前数组的大小调整为3,并创建一个包含上3个值的新数组,因此在执行此操作之后:
arr1 = new [] { 1, 2, 3 };
newArr = new [] { 4, 5, 6 };
Run Code Online (Sandbox Code Playgroud)
最快的方法是什么?我想我将不得不调查非管理角落,但没有任何线索.
更多信息:
简而言之:我想拆分以下输入数组:
int[] arr = new int[] { 1, 3, 4, 29, 31, 33, 35, 36, 37 };
Run Code Online (Sandbox Code Playgroud)
成
arr1 = 1, 3, 4
arr2 = 29, 31, 33, 35, 36, 37
Run Code Online (Sandbox Code Playgroud)
但由于数组大小为3时达到理想速度,因此arr2应分成2个大小均匀的数组.
注意
我知道数组在内存中的实现非常幼稚(好吧,至少在C中,你可以操作数组中的项目数,以便数组调整大小).此外,memory moveWin32 API 中还有一个函数.所以我想这会是最快的:
arr1以便它只包含3个项目arr2大小为3的新数组arr1不再包含的字节arr2我不确定有什么比创建空数组更好,然后使用Array.Copy.我至少希望在内部进行优化:)
int[] firstChunk = new int[3];
int[] secondChunk = new int[3];
Array.Copy(arr1, 0, firstChunk, 0, 3);
Array.Copy(arr1, 3, secondChunk, 0, 3);
Run Code Online (Sandbox Code Playgroud)
老实说,对于非常小的数组,方法调用的开销可能大于仅仅显式分配元素 - 但我认为实际上你将使用略大一些的:)
您可能还会考虑不实际拆分数组,而是使用ArraySegment单独的"数据块".或者也许List<T>用来开始......如果没有更多的背景,很难知道.
如果速度真的很关键,那么使用指针的非托管代码可能是最快的方法 - 但我肯定会检查你是否真的需要去冒险进入不安全的代码.
| 归档时间: |
|
| 查看次数: |
1223 次 |
| 最近记录: |