c# - Fastest way to chop array in two pieces -


i have array, say:

var arr1 = new [] { 1, 2, 3, 4, 5, 6 }; 

now, when array-size exceeds 5, want resize current array 3, , create new array contains upper 3 values, after action:

arr1 = new [] { 1, 2, 3 }; newarr = new [] { 4, 5, 6 }; 

what's fastest way this? guess i'll have unmanaged corner, no clue.


some more info:

  • the arrays have able size without large performance hits
  • the arrays contain int32's
  • purpose of array group numbers in source array without having sort whole list

in short: want split following input array:

int[] arr = new int[] { 1, 3, 4, 29, 31, 33, 35, 36, 37 }; 

into

arr1 =  1, 3, 4 arr2 =  29, 31, 33, 35, 36, 37 

but because ideal speed reached array size of 3, arr2 should split 2 evenly sized arrays.

note

i know array's implementation in memory quite naive (well, @ least in c, can manipulate count of items in array array resizes). there memory move function somewhere in win32 api. guess fastest:

  1. change arr1 contains 3 items
  2. create new array arr2 size 3
  3. memmove bytes aren't in arr1 anymore arr2

i'm not sure there's better creating empty arrays, , using array.copy. i'd @ least hope that's optimized internally :)

int[] firstchunk = new int[3]; int[] secondchunk = new int[3]; array.copy(arr1, 0, firstchunk, 0, 3); array.copy(arr1, 3, secondchunk, 0, 3); 

to honest, small arrays overhead of method call may greater explicitly assigning elements - assume in reality you'll using bigger ones :)

you might consider not splitting array, instead using arraysegment have separate "chunks" of array. or perhaps use list<t> start with... it's hard know without bit more context.

if speed really critical, unmanaged code using pointers may fastest approach - check whether need go there before venturing unsafe code.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -