What is the appropriate way of copying a list to a new list? And What is the most efficient way of copying a list to a new list?
By efficient, not code efficiency, more in the behind the scenes framework sense.
List<String>List2 = List.ToList();
Or:
List<String>List2 = new List<String>();
foreach (string item in List)
{
List2.Add(item);
}
Update:
What about more efficient IL code?
Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.
A list is equal to another list if the two lists are the same type, contain the same number of elements, and the elements occur in the same order.
Given that List<T>
has an IEnumerable<T>
constructor, I would prefer this form:
List<string> newList = new List<string>(otherList);
Edit
And as Ondrej points out in the decompiled code below, the constructor of List<T>
preallocates the size of the array and copies the contents over. This is going to be much quicker than creating a new list and then iterating over the other list adding items individually, especially as in your 2nd example you're not specifying how many items to preallocate.
What ToList does (shortened):
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
return new List<TSource>(source);
}
What List ctor does (shortened):
public List(IEnumerable<T> collection)
{
ICollection<T> collection2 = collection as ICollection<T>;
int count = collection2.Count;
this._items = new T[count];
collection2.CopyTo(this._items, 0);
this._size = count;
}
So the ToList() is much more efficient - it does allocate the space first and then copy all items in one step.
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