Is there a difference between getting an array into a List via array.ToList() method and to do do it via new List(array) in the code below, in terms of its performance and its costs under the hood?

IEnumerable<int> array = new int[]{1,2,3,4,5,6,7,8};
List<int> list_Foo = new List<int>(array);
List<int> list_Bar = array.ToList();
有帮助吗?

解决方案

No; the Enumerable.ToList<T> extension method is just a wrapper that calls the List(IEnumerable<T>) constructor.

The only additional costs you'll incur from ToList are an extra method call and nullity check, which are typically negligible (and might even be eliminated by the JIT compiler).

其他提示

Internally, here's what the call to array.ToList() (Enumerable.ToList()) looks like:

if (source == null)
    throw Error.ArgumentNull("source");

return new List<TSource>(source);

So your second example runs the same code as your first example.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top