.Net 中局部变量的 CLR 垃圾收集
我的一门课中有以下代码段。请注意,这是一个静态方法。我想知道的是,当我创建一个新的 StringBuilder 对象时,旧的会发生什么?它会被垃圾收集吗?
谢谢, 普拉亚格
Public Shared Function CleanUpSql(ByVal s As String) As String
Dim sb As New StringBuilder(s.Trim())
RemoveBrackets(sb)
FixWhiteSpace(sb)
TrimSemicolon(sb)
Return sb.ToString()
End Function
I have a following code segment in one my classes. Please note that this is a static method. What I would like to know is that when I create a new StringBuilder object, what happens to the old one? Does it get garbage collected?
Thanks,
Prayag
Public Shared Function CleanUpSql(ByVal s As String) As String
Dim sb As New StringBuilder(s.Trim())
RemoveBrackets(sb)
FixWhiteSpace(sb)
TrimSemicolon(sb)
Return sb.ToString()
End Function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在执行后的某个时刻,离开您的
CleanUpSql
方法,从而离开定义sb
的范围,即sb 引用的
将被垃圾收集。您不确切知道此收集何时发生(并且您可能不在乎)。StringBuilder
当范围内没有变量引用某个对象时,该对象将受到垃圾回收的影响。
您可以通过
系统请求立即进行收集.GC.Collect()
(在 CLR 的当前实现中,立即执行垃圾收集)。不过,我建议您不要这样做 - 很少需要手动垃圾收集操作。如果您对更多详细信息感兴趣,请从这里开始。
At some point after execution leaves your
CleanUpSql
method, and thereby leaves the scope in whichsb
is defined, theStringBuilder
referenced bysb
will be garbage collected. You don't know exactly when this collection will happen (and you probably don't care).An object is subject to garbage collection when no in-scope variables reference it.
You can request that collection happen immediately with
System.GC.Collect()
(which, in, the current implementation of the CLR, performs garbage collection immediately). I'd suggest that you not do this, however - manual garbage collection manipulation is rarely necessary.If you're interested in more detail, start here.
最终它会发生,在 sub 存在之后的某个时间,因为对对象的引用存在于调用堆栈上。但每当 CLR 认为有需要时就会收集它,而不一定是在您创建新的时候。
Eventually it does, sometime after the sub exists as the reference to the object exist on the call stack. But its collected whenever the CLR feels the need, not necessarily when you make a new one.
您正在堆栈上创建 sb,因此一旦调用 CleanUpSql 退出,sb 就无法访问并且将被垃圾收集。您甚至不需要再次拨打电话。
You are creating sb on stack, so as soon as call to CleanUpSql quits sb is not accessible and would be garbage collected. You even don't need to make another call.