C # list <string> Memory not collected

This code allocates memory but never frees memory. How to force memory collection, GC.Collect () does not work either.

I looked through a lot of posts that ask this question, but everyone replies that the garbage collector will take care of memory, but it never does.

    var list = new List<string>();

    for (var i = 0; i < 10000000; i++)
    {
      list.Add("really long string..................................................................................................");
    }

    for (var i = 0; i < 10000000; i++)
    {
      list[i] = null;
    }

    list.Clear();
-2
source share
2 answers

Here is the codeList<T>.Clear :

// Clears the contents of List.
public void Clear() {
    if (_size > 0)
    {
        Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
        _size = 0;
    }
    _version++;
}

As you can see, the array is saved as-is. This is done for reasons of efficiency. The array is already allocated, there is no need for the GC to collect it, as it will probably be needed again.

Capacity, . ( 0), . :

// Gets and sets the capacity of this list.  The capacity is the size of
// the internal array used to hold items.  When set, the internal 
// array of the list is reallocated to the given capacity.
// 
public int Capacity {
    get {
        Contract.Ensures(Contract.Result<int>() >= 0);
        return _items.Length;
    }
    set {
        if (value < _size) {
            ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
        }
        Contract.EndContractBlock();

        if (value != _items.Length) {
            if (value > 0) {
                T[] newItems = new T[value];
                if (_size > 0) {
                    Array.Copy(_items, 0, newItems, 0, _size);
                }
                _items = newItems;
            }
            else {
                _items = _emptyArray;
            }
        }
    }
}

, ... 8 ( 64- ).

+3

GC.Collect(), , . GC , ...

-2

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


All Articles