简体   繁体   中英

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? 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)

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. 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. 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.

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

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. They also handle copying within the same array, even if the source and destination areas overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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