Answered by:
ICollection.CopyTo() vs. ArrayList.ToArray()

Question
-
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,
idosSaturday, August 4, 2007 4:08 PM
Answers
-
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
Monday, August 6, 2007 2:11 PM -
Using ICollection.CopyTo() is far more efficient. When you use ArrayList, you'll make a duplicate of the collection and iterate it twice.Monday, August 6, 2007 3:20 PM
All replies
-
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
Monday, August 6, 2007 2:11 PM -
Using ICollection.CopyTo() is far more efficient. When you use ArrayList, you'll make a duplicate of the collection and iterate it twice.Monday, August 6, 2007 3:20 PM
-
wow thank you for the explanation ....Thursday, August 9, 2007 1:53 AM
-
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
- Edited by cervedin Sunday, December 13, 2020 12:07 PM formatting
Sunday, December 13, 2020 12:07 PM