.net 中列表中的 Trimexcess

发布于 2024-09-20 00:42:45 字数 49 浏览 5 评论 0原文

用所需的字符串填充列表后,如果不再进一步追加列表,是否应该调用trimexcess?

After filling a list with the the needed strings, if the list won't be further appended, should trimexcess be called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫腻 2024-09-27 00:42:45

加载列表后调用 TrimExcess 可能会节省一些内存。但请记住,如果列表中的项目属于引用类型(并且字符串是引用类型),那么您所节省的只是保存引用所需的内存。

因此,举例来说,如果您有一个分配了 2,000 个项目的 List(of String),但其中只有 1,000 个项目,则调用 TrimExcess 将为您节省1,000 个引用占用的内存。这在 32 位运行时为 4,000 字节,在 64 位运行时为 8,000 字节。

正如 Andrew Hare 提到的,在加载将在内存中停留一段时间的列表后调用 TrimExcess 可能是一件好事。如果您从列表中删除了一大堆内容,那么您也可以考虑调用 TrimExcess,然后您将保留该列表。但是对同一个列表重复调用 TrimExcess ,除非它真的变得很大,否则只是浪费时间。

Calling TrimExcess after you load the list will likely save you some memory. But remember that if the items in your list are of a reference type (and strings are reference types), then all you're saving is the memory required to hold the references.

So, for example, if you have a List(of String) that's allocated for 2,000 items and there are only 1,000 items in it, calling TrimExcess is going to save you the memory occupied by 1,000 references. That's 4,000 bytes on the 32-bit runtime, and 8,000 bytes on the 64-bit runtime.

As Andrew Hare mentioned, calling TrimExcess after loading a list that's going to hang around in memory for a while is probably a good thing. You might also consider calling TrimExcess if you remove a whole bunch of things from a list, and then you're going to keep the list around. But calling TrimExcess repeatedly for the same list, unless it's really getting large, is just wasting time.

关于从前 2024-09-27 00:42:45

当然可以,但请记住

此方法可用于最小化
如果没有 new 则集合的内存开销
元素将被添加到
收藏。 重新分配的成本
复制一个大列表可以是
然而,相当大,因此
如果 TrimExcess 方法不执行任何操作,则
名单中90%以上
容量

我不会太担心这个问题,除非您发现大量分配和稀疏填充的列表占用了太多内存。

You certainly can, but keep in mind:

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 can be
considerable, however, so the
TrimExcess method does nothing if the
list is at more than 90 percent of
capacity
.

I wouldn't worry too much about this unless you have found that large-allocated and sparsely-filled lists are taking up too much memory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文