简体   繁体   中英

IList<T> vs IEnumerable<T>. What is more efficient IList<T> or IEnumerable<T>

What is more efficient way to make methods return IList<T> or IEnumerable<T> ?

IEnumerable<T> it is immutable collection but IList<T> mutable and contain a lot of useful methods and properties.

To cast IList<T> to IEnumerable<T> it is just reference copy:

IList<T> l = new List<T>();
IEnumerable<T> e = l;

To cast IEnumerable<T> to List<T> we need to iterate each element or to call ToList() method:

IEnumerable<T>.ToList(); 

or may pass IEnumerable<T> to List<T> constructor which doing the same iteration somewhere within its constructor.

List<T> l = new List<T>(e);

Which cases you think is more efficient? Which you prefer more in your practice?

As far as efficiency is concerned both are interfaces so the efficiency will depend on the actual concrete class you are returning. As a rule of thumb you should always return the type that's highest in the object hierarchy that works for the consumers of this method. In your case IEnumerable<T> . If the consumers of the class need to add elements, access elements by index, remove elements you are better off using an IList<T> .

So as always in programming: it depends :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM