Explicitly freeing memory in c#

前端 未结 9 727
刺人心
刺人心 2020-12-01 01:12

I\'ve create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:

Dictionary Txns = new Diction         


        
9条回答
  •  鱼传尺愫
    2020-12-01 01:59

    Edit:

    To be fair, setting the reference to null does not free the memory, it assigns it's container to a different address, in this case null. According to MSDN, calling Clear(), does this: "The Count property is set to 0, and references to other objects from elements of the collection are also released. The capacity remains unchanged."

    ...

    You should never call the garbage collector. You are using managed objects with no native resources, trust the garbage collector to clean up after you.

    Besides the size of your dictionary, you don't need to worry about memory, memory isn't your problem, it's garbage collectors problem.

    Calling Clear() will remove the references to any contained object inside, but the capacity remains unchanged.

    On a technical note, collecting memory is expensive and a considerable time consuming operating. Reason being, not only does the GC handle heap memory and clean up your heap, it also sort of defrags the heap. It tries to move memory into contiguous blocks to speed up allocation for when some piece of code makes a large request.

    p.s. How big is your dictionary that you use 155MB of memory?

提交回复
热议问题