关于.net中占用的内存

时间:2012-03-01 09:24:33

标签: .net

Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String
    Dim writer As StringWriter = New StringWriter()
    Dim strXsl As String = String.Empty
    Try
        Dim xslt As New XslCompiledTransform(False)
        xslt.Load(Path.Combine(Application.StartupPath, Xsltpath))
        Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata))
        xslt.Transform(XmlReader, Nothing, writer)
        strXsl = writer.ToString()
        writer.Flush()
        writer.Dispose()
        Return strXsl
    Catch generatedExceptionName As Exception
        Throw
    End Try
End Function

我有上面的函数将xml转换为string。 我可以使用return语句,如下所示

  

return writer.ToString()

而不是下面给出的函数专家

  strXsl = writer.ToString()
        writer.Flush()
        writer.Dispose()
        Return strXsl

最适合最小化内存使用。 在执行函数后在函数中声明的变量和流等等发生了什么?

1 个答案:

答案 0 :(得分:3)

是的,你绝对可以使用

return writer.ToString()
  • 无需刷新StringWriter
  • 实际上通常不需要处理它......但是通常最好处理所有IDisposable实现

更好的解决方案是为编写器使用Using语句,因此总是被释放。摆脱毫无意义的Catch块,只需将代码更改为:

Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String
    Using writer As StringWriter = New StringWriter()
        Dim xslt As New XslCompiledTransform(False)
        xslt.Load(Path.Combine(Application.StartupPath, Xsltpath))
        Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata))
        xslt.Transform(XmlReader, Nothing, writer)
        Return writer.ToString()
    End Using
End Function

您应该非常很少明确地调用Dispose - 您应该总是使用Using statement代替。