我有一个 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/