LINQ: why are different iterators used in the array and list

The question is why does he use this code

  if (source is TSource[])
    return (IEnumerable<TResult>) new Enumerable.WhereSelectArrayIterator<TSource, TResult>((TSource[]) source, (Func<TSource, bool>) null, selector);
  if (source is List<TSource>)
    return (IEnumerable<TResult>) new Enumerable.WhereSelectListIterator<TSource, TResult>((List<TSource>) source, (Func<TSource, bool>) null, selector);
  else
    return (IEnumerable<TResult>) new Enumerable.WhereSelectEnumerableIterator<TSource, TResult>(source, (Func<TSource, bool>) null, selector);
}

instead

  if (source is IList<TSource>)
    return (IEnumerable<TResult>) new Enumerable.WhereSelectIListIterator<TSource, TResult>((List<TSource>) source, (Func<TSource, bool>) null, selector);
  return (IEnumerable<TResult>) new Enumerable.WhereSelectEnumerableIterator<TSource, TResult>(source, (Func<TSource, bool>) null, selector);
}

i mean List<T>, and T[]are both implemented IList<T>, and they both have an index and sell IEnumerable<T>, so both may be the iteration in the same single order, but now use different iterators.

+4
source share
1 answer

This is simply an optimization that covers extremely common cases of filtering an array or list.

  • WhereSelectArrayIterator - . , IList<T> .

  • WhereSelectListIterator , "" List<TSource> struct List<TSource>.Enumerator ( GetEnumerator List<TSource> ), - , IEnumerator<TSource>.

  • WhereSelectEnumerableIterator - , IEnumerator<TSource> - , - . - , - .

+5

Source: https://habr.com/ru/post/1531700/


All Articles