C # list <> should I reduce capacity when deleting items?

I have a List container that can have up to 100,000 items to start with. While the program is running, this list will be slowly empty, should I change capacity when I omit the list?

I did some testing and the runtime seems to be the same thing, but is there a lot of overhead to reduce the capacity of the list? I can find a lot of information about increasing capacity, but not about reducing it.

+6
source share
3 answers

If you have very low memory, this is micro optimization.

Usually there is no need to change the capacity of List<> .

From the TrimExcess :

This method can be used to minimize the overhead of the collection if new items are not added to the collection. However, the cost of redistributing and copying a large List<T> can be significant, so the TrimExcess method does nothing if the list has more than 90 percent capacity. This avoids the high cost of redistribution with a relatively small gain.

+9
source

Do the math: 100,000 elements * 4 bytes per element = roughly 400 KB. If there is too much memory overhead for your program, you can call TrimExcess, since Oded tells you to recreate smaller lists when it gets smaller . (I'm not sure if reducing capacity will actually lead to what you are going to do.)

+3
source

Reducing the capacity of the list is associated with a new array of support and copying data through it, so this is a relatively expensive operation.

In your particular case, I would say that this is not worth it unless you start to run into memory problems.

One strategy that can be used if it should become a real problem is to create a "chunked" implementation of IList<> , which uses not one array, but several, each of a pre-configured size, with additional fragments (fixed-size arrays) added as the previous one fills. It also allows you to shrink a relatively inexpensive list, freeing up unused chunks when deleting items, minimizing memory overhead to one incomplete fragment (the last).

This approach adds performance overhead for all operations in the list, though, since the list should calculate which piece of elements is in and create new pieces as needed. Therefore, this is not useful if you really have a memory problem and a list that really really changes size over time.

+2
source

Source: https://habr.com/ru/post/895685/


All Articles