C# List<> 我应该在删除项目时降低容量吗?

标签 c# list capacity

我有一个 List 容器,它可能有多达 100,000 个项目。当程序运行时,这个列表会慢慢变空,我是否应该在清空列表时更改容量?

我做了一些测试,执行时间似乎是一样的,但是降低列表的容量会有很大的开销吗?我可以找到很多关于增加容量的信息,但没有太多关于降低容量的信息。

最佳答案

除非您的内存量非常低,否则这是一个微优化。

一般情况下,不需要改变List<>的容量。 .

来自 TrimExcess 方法文档:

This method can be used to minimize a collection's memory overhead if no new elements will be added to the collection. The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain.

关于C# List<> 我应该在删除项目时降低容量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7163038/

相关文章:

c# - 传入 XML 大小写敏感问题

c# - 如何通过 Windows 服务使用 Windows Communication Foundation (WCF)

Java StringBuilder(StringBuffer) 的 ensureCapacity() : Why is it doubled and incremented by 2?

c# - 列表的默认容量

c# - "Two-way binding requires Path or XPath"编辑 wpf 数据网格时

c# - 统计通过 asp.net 中的中继器下载文件的次数

list - 列表中的数据框;添加一个名为数据框的新变量

list - 如何在 f# 中编辑可变列表中的项目并允许列表中的其他项目保留其值?

r - 将 R 中的两个列表组合成一个数据框

c++ - 为什么 std::vector 不保留 "double"它的容量,而调整大小呢?