.Net 中局部变量的 CLR 垃圾收集

发布于 2024-11-29 02:31:53 字数 337 浏览 3 评论 0原文

我的一门课中有以下代码段。请注意,这是一个静态方法。我想知道的是,当我创建一个新的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅笑依然 2024-12-06 02:31:53

在执行后的某个时刻,离开您的 CleanUpSql 方法,从而离开定义 sb 的范围,即 sb 引用的 StringBuilder 将被垃圾收集。您不确切知道此收集何时发生(并且您可能不在乎)。

当范围内没有变量引用某个对象时,该对象将受到垃圾回收的影响。

您可以通过系统请求立即进行收集.GC.Collect()(在 CLR 的当前实现中,立即执行垃圾收集)。不过,我建议您不要这样做 - 很少需要手动垃圾收集操作。

如果您对更多详细信息感兴趣,请从这里开始

At some point after execution leaves your CleanUpSql method, and thereby leaves the scope in which sb is defined, the StringBuilder referenced by sb 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.

软糯酥胸 2024-12-06 02:31:53

最终它会发生,在 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.

挽容 2024-12-06 02:31:53

您正在堆栈上创建 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文