How to create and initialize an array with another array?
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.
Use Array.Copy to copy an array
int[] source = new int[5];
int[] target = new int[5];
Array.Copy(source, target, 5);
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");