ToArray()是否针对数组进行了优化?
ReSharper建议将IEnumerable
枚举到列表或数组中,因为我有“可能的多个IEnumerable
枚举” 。
建议的自动代码重新分解有一些内置的优化,以便在调用ToArray()
之前查看IEnumerable
是否已经是一个数组。
var list = source as T[] ?? source.ToArray();
- 这种优化是不是已经内置了原始的LINQ方法?
- 如果没有,那么不这样做的动机是什么?
不,没有这样的优化。 如果source是ICollection
,那么它将被复制到新数组。 这是Buffer
struct的代码, Enumerable
来创建数组:
internal Buffer(IEnumerable source) { TElement[] array = null; int length = 0; ICollection is2 = source as ICollection ; if (is2 != null) { length = is2.Count; if (length > 0) { array = new TElement[length]; // create new array is2.CopyTo(array, 0); // copy items } } else // we don't care, because array is ICollection this.items = array; }
这里是Enumerable.ToArray()
方法:
public static TSource[] ToArray(this IEnumerable source) { if (source == null) { throw Error.ArgumentNull("source"); } Buffer buffer = new Buffer (source); return buffer.ToArray(); // returns items }