Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and initialize an array with another array?

Tags:

arrays

c#

To create and initialize an array with another array I currently do this:

void Foo( int[] a )
{
    int[] b = new int[ a.Length ];
    for ( int i = 0; i < a.Length; ++i )
        b[ i ] = a[ i ];

    // Other code ...
}

Is there a shorter or more idiomatic way of doing this in C#?

It will be great if this can be done in a single statement, like in C++:

vector<int> b( a );

If this cannot be done in a single statement, I will take what I get :-)

like image 457
Ashwin Nanjappa Avatar asked Mar 29 '12 00:03

Ashwin Nanjappa


3 Answers

I like using LINQ for this:

int[] b = a.ToArray();

That being said, Array.Copy does have better performance, if this will be used in a tight loop, etc:

int[] b = new int[a.Length];
Array.Copy(a, b, a.Length);

Edit:

It will be great if this can be done in a single statement, like in C++:

vector b( a );

The C# version of this would be:

List<int> b = new List<int>(a);

List<T> is C#'s equivalent to std::vector<T>. The constructor above works with any IEnumerable<T>, including another List<T>, an array (T[]), etc.

like image 128
Reed Copsey Avatar answered Oct 18 '22 08:10

Reed Copsey


Use Array.Copy to copy an array

     int[] source = new int[5];
     int[] target = new int[5];
     Array.Copy(source, target, 5);
like image 7
Emmanuel N Avatar answered Oct 18 '22 08:10

Emmanuel N


Clone() and ToArray() are syntactically nice because you don't need to pre-allocate a destination array, but in terms of performance, Array.Copy() is the fastest method (see caveat below).

The reason for Array.Copy() being so fast is that it doesn't allocate any memory. However, if you require your arrays to be copied to a new region of memory each time, then Array.Copy() is no longer the fastest method.

Here are my performance results:

Copy: 0 ms
Copy (with allocation): 449 ms
Clone: 323 ms
ToArray: 344 ms

And here's the code I used:

const int arrayLength = 100000;
const int numberCopies = 1000;
var a = new int[arrayLength];
var b = new int[arrayLength];

var stopwatch = new Stopwatch();
for (var i = 0; i < numberCopies; i++) {
    Array.Copy(a, b, arrayLength);
}
Console.WriteLine($"Copy: {stopwatch.ElapsedMilliseconds} ms");

stopwatch.Restart();
for (var i = 0; i < numberCopies; i++) {
    var c = new int[arrayLength];
    Array.Copy(a, c, arrayLength);
}
Console.WriteLine($"Copy (with allocation): {stopwatch.ElapsedMilliseconds} ms");

stopwatch.Restart();
for (var i = 0; i < numberCopies; i++) {
    b = (int[]) a.Clone();
}
Console.WriteLine($"Clone: {stopwatch.ElapsedMilliseconds} ms");

stopwatch.Restart();
for (var i = 0; i < numberCopies; i++) {
    b = a.ToArray();
}
Console.WriteLine($"ToArray: {stopwatch.ElapsedMilliseconds} ms");
like image 3
DinoM Avatar answered Oct 18 '22 07:10

DinoM