Will these variables be garbage
I was practicing my coding chops today and solving the "remove all elements of a certain value from a linked list" problem today. The solution I came up with was
public void RemoveAll ( T val )
{
if(_root == null)
return;
if(_root.Value == val)
{
_root = _root.Next;
RemoveAll(val);
}
Node last = _root,
cur = _root.Next;
while(cur != null)
{
if(cur.Value == val)
last.Next = cur.Next;
else
last = cur;
cur = cur.Next;
}
}
and here's my question:
When cur.Value == val
I'm doing something like changing the list from
A -> B -> C
to
A -> C
Will the compiler or run-time environment see that B
is no longer in use and dispose of it? Or should I do that explicitely?
I have a second question which is whether a call stack blows up for recursive void
methods. As you see here, there is a chance of the method calling itself. But since it's a method that doesn't return a value, can't the run-time environment just wipe the data about the last call? There is no reason for it to remain in memory (right?).
Will the compiler or run-time environment see that B is no longer in use and dispose of it? Or should I do that explicitely?
GC, when it runs, will realize there is no active references to that object and clean it up (assuming nobody else holds a reference to that object). You can't manually clean a single object in .NET. In .NET memory is managed and cleaned by Garbage Collector as needed.
I have a second question which is whether a call stack blows up for recursive void methods. As you see here, there is a chance of the method calling itself. But since it's a method that doesn't return a value, can't the run-time environment just wipe the data about the last call? There is no reason for it to remain in memory (right?).
You're describing tail recursion. C# compiler will not generate tail-recursive calls. Becaus eof that it's possible you're going to run into StackOverflowException
if your recursion is too deep.
That limitation is not a CLR limitation - .NET Framework does support tail calls. It's C# compiler which doesn't emit tail IL opcode. You can get Tail Recursion working in .NET Framework when generating IL by hand or when using F#, which generates tail calls whenever appropriate.
See https://stackoverflow.com/a/15865150/1163867 for more details.
PS. I think your code has a bug. Looks like you should return early after recursive call into RemoveAll
:
if(_root.Value == val)
{
_root = _root.Next;
RemoveAll(val);
return;
}
链接地址: http://www.djcxy.com/p/80626.html
上一篇: .mp4文件不能用chrome播放
下一篇: 这些变量是垃圾吗?