Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to extend array

Tags:

arrays

c#

c#-4.0

I am looking for fastest way to extend an array. No matter if only for length + 1 or length + x it has to be the most fastest way.

Here is an example:

var arr = new int [200];
for(int = 0; i < 200; i++)
   arr[i] = i;

And now I want to extend arr for 5 items beginning at index position 20.

var arr2 = new int [] { 999, 999, 999, 999, 999 }

How do I place arr2 inside arr by using most fast way in terms of performance?

The result shall look like this 0,1,2,3,4....20, 999, 999, 999, 999, 999, 21, 22, 23, 24....199

like image 434
snowy hedgehog Avatar asked Apr 19 '26 23:04

snowy hedgehog


1 Answers

Create a new array which is the size you want, then use the static Array.Copy method to copy the original arrays into the new one.

You can't "extend" an array, you can only create a bigger one and copy the original into it.

Also, consider using List<int> or LinkedList<> instead of an array, unless you require extremely fine-grained control over what is in memory.

like image 107
RobSiklos Avatar answered Apr 22 '26 11:04

RobSiklos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!