pencilCake
pencilCake

Reputation: 53223

Is there a difference between new List<int>(array) and array.ToList()?

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();

Upvotes: 0

Views: 208

Answers (2)

Douglas
Douglas

Reputation: 54877

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).

Upvotes: 4

Grant Winney
Grant Winney

Reputation: 66439

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.

Upvotes: 2

Related Questions