ToArray()是否针对数组进行了优化? [英] Is ToArray() optimized for arrays?
问题描述
ReSharper建议将IEnumerable<T>
枚举到列表或数组,因为我有可能IEnumerable<T>
的多个枚举" .
ReSharper suggested to enumerate an IEnumerable<T>
to a list or array since I had "possible multiple enumerations of IEnumerable<T>
".
建议的自动代码重构具有一些内置的优化功能,可以在调用ToArray()
之前查看IEnumerable<T>
是否已经是数组.
The automatic code re-factoring suggested has some optimization built in to see whether IEnumerable<T>
already is an array before calling ToArray()
.
var list = source as T[] ?? source.ToArray();
- 此优化是否已内置于原始LINQ方法中?
- 如果没有,那么这样做的动机是什么?
推荐答案
不,没有这样的优化.如果source是ICollection
,则它将被复制到新数组.这是Buffer<T>
结构的代码,被Enumerable
用于创建数组:
Nope, there is no such optimization. If source is ICollection
, then it will be copied to new array. Here is code of Buffer<T>
struct, which used by Enumerable
to create array:
internal Buffer(IEnumerable<TElement> source)
{
TElement[] array = null;
int length = 0;
ICollection<TElement> is2 = source as ICollection<TElement>;
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<TElement>
this.items = array;
}
这是Enumerable.ToArray()
方法:
public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
Buffer<TSource> buffer = new Buffer<TSource>(source);
return buffer.ToArray(); // returns items
}
这篇关于ToArray()是否针对数组进行了优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!