Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an advantage to using Array.Empty vs. new List when initializing a List property?

Is there an advantage in one of these approaches over the other as far as performance?

public class Person
{
  public List<string> Favorites {get; set;} = new List<string>();
}

or

public class Person
{
  public List<string> Favorites {get; set;} = Array.Empty<string>().ToList();
}

I understand that there are advantages of using Enumerable.Empty<> and Array.Empty<> when working with these types. But I’m wondering specifically about when the property is of type List<>. My instinct says that both approaches ultimately allocate a List object, so they are essentially equivalent. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Array.Empty<>() is a very useful way of making empty arrays due to empty array optimization, but you can’t do better than new List() for an empty list. .ToList() eventually needs to invoke a list constructor anyway; and the cheapeast list constructor is the default constructor.

So, no point in Array.Empty<>().ToList().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading