Explanation why IEnumerable is more efficient than a List

前端 未结 7 1809
北荒
北荒 2021-01-30 08:35

I keep hearing that in .net 3.5 you should use IEnumerable over a List, but I can’t find any reference materials or articles that explain why it’s so much more proficient. Does

7条回答
  •  无人共我
    2021-01-30 09:12

    IEnumerable is an interface that is implemented by List. I suspect the reason you're hearing that IEnumerable should be used is because it's a less constrictive interface requirement.

    For example, consider the following method signature:

    void Output(List foos) 
    { 
        foreach(var foo in foos) { /* do something */ }
    }
    

    This method requires that it be passed a concrete implementation of a List. But it's just doing something in-order. It doesn't really need random access or any of the other things that a List or even an IList give it. Instead, the method should accept an IEnumerable:

    void Output(IEnumerable foos) 
    { 
        foreach(var foo in foos) { /* do something */ }
    }
    

    Now we're using the most general (least specific) interface that supports the operations that we need. This is a fundamental aspect of OO-design. We've decreased coupling by requiring only what we need, and not a whole lot else besides. We've also created a more flexible method because the foos parameter might be a Queue, a List, anything that implements IEnumerable. We aren't forcing the caller to convert their data structure to a List unnecessarily.

    So it isn't that IEnumerable is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable is a more efficient design construct because it's a more specific indication of what your design requires. (Though this can lead to runtime gains in specific cases.)

提交回复
热议问题