Clone() và ToArray() là cú pháp tốt đẹp bởi vì bạn không cần tiền phân bổ một mảng đích, nhưng về hiệu suất, Array.Copy() là phương pháp nhanh nhất (xem báo trước bên dưới).
Lý do cho Array.Copy() quá nhanh đến nỗi nó không cấp phát bộ nhớ. Tuy nhiên, nếu bạn yêu cầu mảng của bạn được sao chép vào một vùng bộ nhớ mới mỗi lần, thì Array.Copy() không còn là phương thức nhanh nhất.
Dưới đây là kết quả thực hiện của tôi:
Copy: 0 ms
Copy (with allocation): 449 ms
Clone: 323 ms
ToArray: 344 ms
Và đây là đoạn code tôi sử dụng:
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");
Không thể bạn chỉ cần sử dụng 'Array.Copy'? –
phải là cách để sao chép tất cả bộ nhớ trực tiếp ... trong C++ http://stackoverflow.com/questions/3902215/using-memcpy-to-copy-a-range-of-elements-from-an-array –
http: // stackoverflow.com/questions/5655553/whats-the-most-effective-to-copy-elements-of-ac-sắc nét-đa chiều-arr –