views:

23

answers:

2

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

+2  A: 

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.

Andrew Hare
Say I have a few hundred lists in objects where each list has ~500-2000 strings of ~40 characters each. It wouldn't hurt to call trimexcess right?
It would depend how often you wanted to call it and the type of application. Would you call it 100s of times a minute, not really, would you call it after loading the lists out of a file once? Probably. Remember that lists doubles its size when it runs out of memory, so you would most likely gain something - but RAM is cheap, especially at even with ~8,000,000 characters...
Tim Joseph
+2  A: 

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.

Jim Mischel