최고의 답변자
ICollection.CopyTo() vs. ArrayList.ToArray()

질문
-
Dear all,
I want to convert a ICollection instance to a normal array. But then I realized these two ways will give me a Array object.
Just curious, which one is better (efficient in memory or faster).
I usually use CopyTo as follows: (assume we have ICollection collection has been initialized)
object[] array = new object[collection.Size];
collection.CopyTo(array, 0);
And for ToArray()
object[] array = new ArrayList(collection).ToArray();
Thank you,
idos2007년 8월 4일 토요일 오후 4:08
답변
-
Hi Idos,
The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array.
The CopyTo( ) method copies its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify.
The ToArray( ) method returns a new array with the contents of the type's elements.
Thus, as far as I know, the CopyTo( ) method is better.
In the case of a ArrayList, ToArray( ) would return a new array containing the elements in the ArrayList. CopyTo( ) would copy the ArrayList over a pre-existing array.
Copying from a Collection Type to an Array
Best Regards,
Martin Xie
2007년 8월 6일 월요일 오후 2:11
모든 응답
-
Hi Idos,
The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array.
The CopyTo( ) method copies its elements to an existing one-dimensional array, overwriting the contents of the array beginning at the index you specify.
The ToArray( ) method returns a new array with the contents of the type's elements.
Thus, as far as I know, the CopyTo( ) method is better.
In the case of a ArrayList, ToArray( ) would return a new array containing the elements in the ArrayList. CopyTo( ) would copy the ArrayList over a pre-existing array.
Copying from a Collection Type to an Array
Best Regards,
Martin Xie
2007년 8월 6일 월요일 오후 2:11 -
array.CopyTo(T[] target, int i) copies the values from array into target, starting at index i
array.ToArray() creates a buffer and and then calls CopyTo() internally
They are basically the same from a performance perspective and I would recommend ToArray() is most use-cases
- 편집됨 cervedin 2020년 12월 13일 일요일 오후 12:07 formatting
2020년 12월 13일 일요일 오후 12:07