Search code examples
c#asp.netlistcollections

Is returning List<T> from method differ in performance from returning Collection<T>?


We have a web project that contain its business methods in a class library project called "Bll.dll"
some methods of Bll.dll return List<> ...
from a source - that i don't remember now - told that returning Collection<> is better than returning List<>
Is it a valid ?
Note that i don't make any process on values returned from BLL methods .. just view it in a web page


Solution

  • Collection<T> is implemented, IIRC, as a wrapper around an IList<T>, of which the default implementation is List<T>. Therefore a Collection<T> has at least one more abstraction than a List<T>, but in general this won't be a bottleneck. In fact, you might consider returning IList<T>.

    Edit: here is the constructor of Collection<T>, courtesy of reflector:

    public Collection()
    {
        this.items = new List<T>();
    }
    

    so indeed, this wraps a layer of abstraction. The plus side of this is that you can add your own validation etc by subclassing Collection<T> (which is not possible when using List<T> directly or via subclassing, since there are no interesting virtual methods).

    The other thing to consider is that they will have the same overall performance in terms of "O" (assuming you use the default List<T> implementation). Indexer lookup will be O(1), etc