Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to copy/fill a large array with a smaller array in C#?

I have a large int[] array and a much smaller int[] array. I want to fill up the large array with values from the small array, by repeat copying the small array into the large array until it is full (so that large[0] = large[13] = large[26] ... = small[0] etc.). I already have a simple method:

int iSource = 0;
for (int i = 0; i < destArray.Length; i++)
{
    if (iSource >= sourceArray.Length)
    {
        iSource = 0; // reset if at end of source
    }
    destArray[i] = sourceArray[iSource++];
}

But I need something more elegant, and hopefully faster.

like image 467
MusiGenesis Avatar asked Dec 12 '25 04:12

MusiGenesis


1 Answers

Interestingly the winning answer is the slowest with the provided source array!

The solution I was going to propose was

for (int i = 0; i < destArray.Length; i++)
{
    destArray[i] = sourceArray[i%sourceArray.Length];
}

but when i tested the perf over 100000 iterations using the inputs in the answering question it performed worse than the questioners loop.

here is the output from my little test app

array copy 164ms      (Nelson LaQuet's code) 
assign copy 77ms      (MusiGenesis code)
assign mod copy 161ms (headsling's code)
like image 87
headsling Avatar answered Dec 14 '25 16:12

headsling



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!