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?
IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.
IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.
Generally, it's better to return IEnumerable<T> , as long as that has everything the caller needs.
You use IEnumerable when you want to loop through the items in a collection. IList is when you want to add, remove, and access the list contents out of order.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With