简体   繁体   English

C#中清除数组部分或四处移动部分​​的最快方法

[英]Fastest way in c# to clear portions of an array or move portions around

what is the fastest way in c# to manipulate array of short ints? 在C#中操作短整数数组的最快方法是什么? I miss things like memset or mempcy and memmove. 我很想念记忆或记忆和记忆。

I need to clear (set to 0) portions of an array and move portions around (like shifting values to different indices) 我需要清除(设置为0)数组的一部分并四处移动(例如将值移动到不同的索引)

To be more precise: I have a huge array that I have to modify. 更准确地说:我必须修改大量数组。 Sometime I have to clear portions of that array, setting them to 0. Other times I have to shift data around inside the same array. 有时我必须清除该数组的部分,将它们设置为0。有时,我必须在同一数组内移动数据。 I therefore need to operate on the same Array already allocated 因此,我需要对已经分配的同一数组进行操作

An array in c# will already be allocated with the default value of the type, so memset to 0 is usually irrelevant. c#的数组已经分配了该类型的默认值,因此memset0通常是无关紧要的。 You will never get a " dirty " array on construction. 您将永远不会在构造上得到“ 肮脏的 ”阵列。

For copy operations, you can use Array.Copy for typed copying or Buffer.Blockcopy for raw byte copying. 对于复制操作,可以使用Array.Copy进行类型化复制,或者使用Buffer.Blockcopy进行原始字节复制。

Both of these support copying from/to the same array, you just have to be careful not to provide overlapping idices. 这两个都支持从/复制到同一阵列, 您只需要注意不要提供重叠的索引。

Edit: 编辑:

For clearing out data you can use Array.Clear 为了清除数据,您可以使用Array.Clear

For clearing a part of an array you can just use a method like: 要清除数组的一部分,您可以使用以下方法:

public static void Clear(short[] arr, int start, int len) {
  int end = start + len;
  for (int i = start; i < end; i++) arr[i] = 0;
}

For copying, you can use Array.Copy or Buffer.BlockCopy methods. 对于复制,可以使用Array.CopyBuffer.BlockCopy方法。 They also handle copying within the same array, even if the source and destination areas overlap. 即使源区域和目标区域重叠,它们也可以处理同一阵列中的复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM