gpt4 book ai didi

c# - 以容量列出?

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:21 26 4
gpt4 key购买 nike

当我们为 IEnumerable 执行 .ToList() 时,列表可能会在扫描 IEnumerable 时重新分配,因为它不知道预先的大小。如果大小已知,是否有一种简单的方法可以避免性能损失?用所需的容量初始化 List 然后将 IEnumerable 复制到其中有什么效果吗?理想情况下像 .ToList(capacity) 这样简单的东西(它不存在)。

最佳答案

在容量是 IEnumerable<T> 的一部分的情况下那也是一个 ICollection<T> ,图书馆将以正确的容量分配。

这是一个reference implementation of List<T>(IEnumerable<T> source) ,当您调用 ToList() 时调用:

public List(IEnumerable<T> collection) {
if (collection==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();

ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0) {
_items = _emptyArray;
} else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
} else {
_size = 0;
_items = _emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.

using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Add(en.Current);
}
}
}
}

注意构造函数在 collection 时的行为工具 ICollection<T> : 而不是迭代内容并调用 Add对于每个项目,它分配内部 _items数组,并将内容复制到其中而不重新分配。

在容量嵌入类实现的情况下 IEnumerable<T> ,您可以使用标准方法的组合轻松地自己定义一个:

public static class ToListExtension {

public static List<T> ToList<T>(this IEnumerable<T> source, int capacity)
{
var res = new List<T>(capacity);
res.AddRange(source);
return res;
}

}

关于c# - 以容量列出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208429/

26 4 0
文章推荐: c# - 如何使用 MathDotNet 库应用零相位滤波器?
文章推荐: jquery - 我想在通过 Bootstrap 的 "img-responsive"调整图像大小时调整
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com