它是更好地销毁所有对象或只是让垃圾收集器做的工作?它是、对象、垃圾、更好地

2023-09-07 09:32:49 作者:软肋

我有类似如下的功能:

Public Function testFunction(ByVal input_string As String) As String

    Dim s As New StringBuilder()
    Dim c As Char
    For i As Integer = 0 To input_string.Length - 1
        c = input_string.Chars(i)
        s.Append(c)
    Next
    Return s.ToString

End Function

但我想知道这是否是最好明确摧毁任何对象,像这样:

but I want know if it's better to explicitly destroy any object, like this:

    Public Function testFunction(ByVal input_string As String) As String

    Dim s As New StringBuilder()
    Dim c As Char
    For i As Integer = 0 To input_string.Length - 1
        c = input_string.Chars(i)
        s.Append(c)
    Next

    Dim t As String = s.ToString
    s = Nothing

    Return t

End Function

或只是让垃圾收集器做的工作为我们?

or just let the garbage collector do the job for us?

以上两种功能的工作,但我只想知道性能的最佳实践...

Both the above functions work, but I want only know the best practice for performance...

谢谢

推荐答案

它的总是的更好,让垃圾收集器做的工作给你。想想看,这样的:程序员很多比你更聪明(我)精心优化的垃圾收集程序,使生活更简单,无痛为您服务。这是不可能的,我们可以做一个更好的工作自我,更有可能的是,我们只会干扰。

It's always better to let the garbage collector do the job for you. Think about it like this: a programmer much smarter than you (and I) carefully optimized the garbage collection routine to make life much simpler and painless for you. It's unlikely that we can do a better job ourselves, and more likely that we'll just interfere.

基本上,这是实例化为局部变量对象将符合垃圾收集,尽快为他们掉出的范围(即,该方法执行完毕)。你的的StringBuilder 对象将是垃圾回收,每当垃圾回收器运行(这是另一件事,你不用担心,有没有办法知道下一次GC将运行)。

Basically, objects that are instantiated as local variables will become eligible for garbage collection as soon as they fall out of scope (i.e., that method finishes execution). Your StringBuilder object is going to be garbage collected whenever the garbage collector runs (which is another thing you don't have to worry about—there is no way to know the next time the GC will run).

设置对象为没有字面上不执行任何操作(注意,这是比pre-.NET的Visual Basic的版本有所不同)。它通常会被优化出由编译器在释放模式,并且即使不是这样,它没有帮助你在至少

Setting an object to Nothing literally does nothing (note that this is different than pre-.NET versions of Visual Basic). It will generally be optimized out by the compiler in Release mode, and even if it isn't, it's not helping you in the least.

然而,如果一个对象具有 处置 方式,你应该调用它。或者更好的是,包装在一个 使用语句。但是,还是有没有理由将其引用没有

However, if an object has a Dispose method, you should be calling it. Or better yet, wrap it in a Using statement. But there's still no reason to set its reference to Nothing.

 
精彩推荐
图片推荐