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 :-)
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With