copy array to List

  • Thread starter Thread starter John Grandy
  • Start date Start date
J

John Grandy

What is the most performant way to copy an array's elements into a List ?
 
John Grandy said:
What is the most performant way to copy an array's elements into a List ?

string[] astrTest = new string[5];

astrTest[0] = "One";

astrTest[1] = "One";

astrTest[2] = "One";

astrTest[3] = "One";

astrTest[4] = "One";

List<string> lstTest = new List<string>(astrTest);
 
John Grandy said:
What is the most performant way to copy an array's elements into a List ?

I always use the .AddRange() method on List<T>. I've never profiled it to
see if there's a faster way, but I would think not.

Certainly, this is the best method in terms of Code Clarity and Maintenance,
which are generally way more important than the actual performance.
 
Chris Mullins said:
I always use the .AddRange() method on List<T>. I've never profiled it to
see if there's a faster way, but I would think not.

Certainly, this is the best method in terms of Code Clarity and
Maintenance, which are generally way more important than the actual
performance.

I should add that, if it's practical, you should allocate your List<T> with
the correct capacity.

This means if you have a populated array myArray, you should:

List<string> myList = new List<string>(myArray.Length);
myList.AddRange(myArray);

Doing this will avoid all sorts of unnecessary memory allocations and array
resizes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top