3

Consider the following code:

static IEnumerable<int> GetItems()
{
    return Enumerable.Range(1, 10000000).ToArray();  // or: .ToList();
}

static void Main()
{
    int count = GetItems().Count();
}

Will it iterate over all the 10 billion integers and count them one-by-one, or will it use the array's Length / list's Count properties?

Johan Hirsch
  • 557
  • 4
  • 21

2 Answers2

4

If the IEnumerable is an ICollection, it will return the Count property.

Here's the source code:

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    ICollection<TSource> collectionoft = source as ICollection<TSource>;
    if (collectionoft != null) return collectionoft.Count;
    ICollection collection = source as ICollection;
    if (collection != null) return collection.Count;
    int count = 0;
    using (IEnumerator<TSource> e = source.GetEnumerator())
    {
        checked
        {
            while (e.MoveNext()) count++;
        }
    }
    return count;
}

An array implements ICollection<T>, so it doesn't need to be enumerated.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

The code will first put all the integers into array (due to your .ToArray() call), and then return the length of the array (since all arrays implement ICollection), which the actual code calls. It will not count all items in the array one by one.

Community
  • 1
  • 1
martijn
  • 1,417
  • 1
  • 16
  • 26
  • I cannot detect an array in the source code presented by @Jakub, and I don't see a reason why one should create one. – Peter - Reinstate Monica Sep 30 '15 at 10:34
  • 2
    @PeterSchneider There is in the code from OP, just read: `return Enumerable.Range(1, 10000000).ToArray(); ` The code clearly calls `ToArray`. – Patrick Hofman Sep 30 '15 at 10:35
  • Oh. I misunderstood. Well. I guess the answer to the OP is "you just did something insane but the compiler will not add insanity on top". I assume that C# compilers are allowed to apply the as-if rule, so the compiler is allowed to do nothing at all (since the program has no observable effect). If you print the count, the compiler is free to just print 10000000, no arrays or anything. – Peter - Reinstate Monica Sep 30 '15 at 10:43
  • No, since it doesn't know there aren't side effects. It will create the array, no matter how useless it is. – Patrick Hofman Sep 30 '15 at 10:49
  • @PatrickHofman You can see there are no side effects; I can see it. The compiler can see it. It's all there, in plain view. The complete source code is even in a single translation unit. Or am I missing something? – Peter - Reinstate Monica Sep 30 '15 at 10:55
  • Yes, compilers are dumb @Peter. – Patrick Hofman Sep 30 '15 at 10:57