C# - Garbage Collection

2019-03-09 04:52发布

Ok so I understand about the stack and the heap (values live on the Stack, references on the Heap).

When I declare a new instance of a Class, this lives on the heap, with a reference to this point in memory on the stack. I also know that C# does it's own Garbage Collection (ie. It determines when an instanciated class is no longer in use and reclaims the memory).

I have 2 questions:

  1. Is my understanding of Garbage Collection correct?
  2. Can I do my own? If so is there any real benefit to doing this myself or should I just leave it.

I ask because I have a method in a For loop. Every time I go through a loop, I create a new instance of my Class. In my head I visualise all of these classes lying around in a heap, not doing anything but taking up memory and I want to get rid of them as quickly as I can to keep things neat and tidy!

Am I understanding this correctly or am I missing something?

标签: c# stack heap
9条回答
对你真心纯属浪费
2楼-- · 2019-03-09 05:37

Read the following article by Microsoft to get a level of knowledge about Garbage Collection in C#. I'm sure it'll help anyone who need information regarding this matter.

Memory Management and Garbage Collection in the .NET Framework

查看更多
Deceive 欺骗
3楼-- · 2019-03-09 05:39

First off, to Erics seminal post about The truth about value types

Secondly on Garbage collection, the collector knows far more about your running program than you do, don't try to second guess it unless you're in the incredibly unlikely situation that you have a memory leak.

So to your second question, no don't try to "help" the GC.

I'll find a post to this effect on the CG and update this answer.

查看更多
Viruses.
4楼-- · 2019-03-09 05:41

If you are interested in performance of some areas in your code when writing C#, you can write unsafe code. You will have a plus of performance, and also, in your fixed block, the garbage collector most likely will not occur.

查看更多
登录 后发表回答