Explanation why IEnumerable is more efficient than a List

前端 未结 7 1791
北荒
北荒 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:35

    It isn't a question of efficiency (although that may be true) but of flexibility.

    Your code becomes more re-usable if it can consume an IEnumerable instead of a List. AS to efficient consider this code:-

     function IEnumerable<int> GetDigits()
     {
    
        for(int i = 0; i < 10; i++)
           yield return i
     }
    
     function int Sum(List<int> numbers)
     {
        int result = 0; 
        foreach(int i in numbers)
          result += i;
    
        return i;
     }
    

    Q: How do I take the set of numbers generated by GetDigits and get Sum to add them up?
    A: I need to load the set of numbers from GetDigits into a List object and pass that to the Sum function. This uses memory as all the digits need to be loaded into memory first before they can be summed. However changing the signature of Sum to:-

     function int Sum(IEnumerable<int> numbers)
    

    Means I can do this:-

     int sumOfDigits = Sum(GetDigits());
    

    No list is loaded into memory I only need storage for the current digit and the accumulator variable in sum.

    0 讨论(0)
提交回复
热议问题