Should be an easy one. Let's say I have the following code:
void Method()
{
AnotherMethod(new MyClass());
}
void AnotherMethod(MyClass obj)
{
Console.WriteLine(obj.ToString());
}
If I call 开发者_如何学JAVA"Method()", what happens to the MyClass object that was created in the process? Does it still exist in the stack after the call, even though nothing is using it? Or does it get removed immediately?
Do I have to set it to null to get GC to notice it quicker?
After the call to Method completes, your MyClass
object is alive but there are no references to it from a rooted value. So it will live until the next time the GC runs where it will be collected and the memory reclaimed.
There is really nothing you can do to speed up this process other than to force a GC. However this is likely a bad idea. The GC is designed to clean up such objects and any attempt you make to make it faster will likely result in it being slower overall. You'll also find that a GC, while correctly cleaning up managed objects, may not actually reduce the memory in your system. This is because the GC keeps it around for future use. It's a very complex system that's typically best left to it's own devices.
If I call "Method()", what happens to the MyClass object that was created in the process?
It gets created on the GC heap. Then a reference to its location in the heap is placed on the stack. Then the call to AnotherMethod happens. Then the object's ToString method is called and the result is printed out. Then AnotherMethod returns.
Does it still exist in the stack after the call, even though nothing is using it?
Your question is ambiguous. By "the call" do you mean the call to Method, or AnotherMethod? It makes a difference because at this point, whether the heap memory is a candidate for garbage collection depends upon whether you compiled with optimizations turned on or off. I'm going to slightly change your program to illustrate the difference. Suppose you had:
void Method()
{
AnotherMethod(new MyClass());
Console.WriteLine("Hello world");
}
With optimizations off, we sometimes actually generate code that would be like this:
void Method()
{
var temp = new MyClass();
AnotherMethod(temp);
Console.WriteLine("Hello world");
}
In the unoptimized version, the runtime will actually choose to treat the object as not-collectable until Method returns, after the WriteLine. In the optimized version, the runtime can choose to treat the object as collectible as soon as AnotherMethod returns, before the WriteLine.
The reason for the difference is because making object lifetime more predictable during debugging sessions often helps people understand their programs.
Or does it get removed immediately?
Nothing gets collected immediately; the garbage collector runs when it feels like it ought to run. If you need some resource like a file handle to be cleaned up immediately when you're done with it then use a "using" block. If not, then let the garbage collector decide when to collect memory.
Do I have to set it to null to get GC to notice it quicker?
Do you have to set what to null? What variable did you have in mind?
Regardless, you do not have to do anything to make the garbage collector work. It runs on its own just fine without prompting from you.
I think you're overthinking this problem. Let the garbage collector do its thing and don't stress about it. If you're having a real-world problem with memory not being collected in a timely manner, then show us some code that illustrates that problem; otherwise, just relax and learn to love automatic storage reclamation.
Actually, the instance will be declared on the heap, but have a look at Eric Lipper's article, The Stack is an Implementation Detail.
In any case, because there will be no more references to the instance after the function executes, it will be (or, more accurately, can be) deleted by the garbage collector at some undefined point in the future. As to exactly when that happens, it's undefined, but you also (essentially) don't need to worry about it; the GC has complicated algorithms that help it determine what and when to collect.
Does it still exist in the stack after the call
Semantics are important here. You asked if it still exists on the stack after the method call. The answer there is "no". It was removed from the stack. But that's not the final story. The object does still exist, it's just no longer rooted. It won't be destroyed or collected until the GC runs. But at this point it's no longer your concern. The GC is much better at deciding when to collect something than you or I are.
Do I have to set it to null to get GC to notice it quicker?
There's almost never a good reason to do that, anyway. The only time that helps is if you have a very long running method and an object that you are done with early that otherwise won't go out of scope until the end of the method. Even then, setting it to null will only help in the rare case where the GC decides to run during the method. But in that case you're probably doing something else wrong as well.
In C# the new MyClass() is scoped only to live inside Method() while it is active. Once that AnotherMethod() is finished executing, it is out of scope and gets unrooted. It then remains on the heap until the GC runs its collection cycle and identifies it as an unreferenced memory block. So it is still "alive" on the heap but it is inaccessible.
The GC keeps track of what objects can possibly still be referenced later in the code. It then, at intervals, checks to see if there are any objects still alive that could not possibly be referenced later in the code, and cleans them up.
The mechanics of this are somewhat complex, and when these collections will happen depends on a variety of factors. The GC is designed to do these collections at the most optimal time (that it can establish) and so, while it is possible to force it to do a collection, it is almost always a bad idea.
Setting the variable to null will have very little overall effect on how soon the object is dealt with. While it can, in some small corner cases, be of benefit it is not worth littering your code with redundant assignments which will not affect your codes performance and only harm readability.
The GC is designed to be as effective as possible without you needing to think about it. To be honest, the only thing you really need to be mindful of is being careful when allocating really large objects that will stay alive for a long time, and that's generally quite rare in my experience.
As far as I know, the object is only valid inside your method context. After the method "Method()" is executed it is added to the dispose queue.
精彩评论