Clone() e ToArray() sono sintatticamente bello perché non è necessario pre-allocare una matrice di destinazione, ma in termini di prestazioni, Array.Copy() è il metodo più veloce (vedi avvertimento di seguito).
Il motivo per cui Array.Copy() è così veloce è che non alloca memoria. Tuttavia, se si richiede che gli array vengano copiati in una nuova area di memoria ogni volta, quindi Array.Copy() non è più il metodo più veloce.
Qui ci sono i miei risultati di performance:
Copy: 0 ms
Copy (with allocation): 449 ms
Clone: 323 ms
ToArray: 344 ms
Ed ecco il codice che ho usato:
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");
Impossibile basta usare 'Array.Copy'? –
dovrebbe essere un modo per copiare tutta la memoria direttamente ... in C++ http://stackoverflow.com/questions/3902215/using-memcpy-to-copy-a-range-of-elements-from-an-array –
http: // StackOverflow.it/questions/5655553/whats-the-most-efficient-way-to-copy-elements-of-ac-sharp-multidimensionale-arr –