可以在.NET抖动优化掉一个虽然XmlReader.Read循环?NET、XmlReader、Read

2023-09-06 17:33:29 作者:繁花飘落谁去留

我问什么,我认为实际的问题是一个单独的问题(现已删除)。

请问.NET抖动没有真正执行这个循环:

Could the .NET Jitter not actually execute this loop:

Private Shared Sub CheckXmlValidity(ByVal textReader As System.IO.StreamReader)
  Try
    ' Check for "interesting" xml documents.
    Dim settings = New System.Xml.XmlReaderSettings()
    settings.XmlResolver = Nothing
    settings.MaxCharactersInDocument = 655360
    ' Successfully parse the file, otherwise an XmlException is to be thrown.
    Dim reader = System.Xml.XmlReader.Create(textReader, settings)
    Try
      While reader.Read()
        'Just checking.
      End While
    Finally
      reader.Close()
    End Try
  Catch ex As Exception
    Throw New HttpException(500, "Invalid Xml data", ex)
  End Try
End Sub

我希望的不完全,因为这可能被抛出的异常的副作用,但我只是检查...

I would hope not exactly because of the side-effect of the exceptions that could be thrown, but I'm just checking...

推荐答案

在JITer,真是任何优化,只能删除这对问题的执行没有影响的项目。证明一个方法没有效果是很难做到的.NET。特别是因为每一个方法调用可以有效果,如果源对象是(它会抛出一个异常)。因此,即使方法被称为是一个空操作不能在没有插入检查各种完全删除(1)

The JITer, and really any optimizer, can only remove items which have no effect on the execution of the problem. Proving a method has no effect is very hard to do in .Net. Particularly because every method call can have an effect if the source object is null (it would throw an exception). Hence even methods are known to be a no-op can't be fully removed without inserting a null check of sorts (1)

在这种情况下, XmlReader.Read 是在未密封的类型,就更难了一个摘要方法。该JITer只能删除该调用,如果它知道,每一个实施 XmlReader.Read 的是一个空操作,因此没有任何影响。它永远不能知道这个,但因为的XmlReader 的派生的数量也不是固定的。一个新的DLL可以在任何时候下载的XmlReader 的新推导其中有一个有意义的定义,因此不能被优化掉。

In this case XmlReader.Read is an abstract method on an unsealed type which is even harder. The JITer could only remove this call if it knew that every implementation of XmlReader.Read was a no-op and hence had no effect. It can't ever know this though because the number of derivations of XmlReader is not a fixed set. A new DLL could be loaded at any time with a new derivation of XmlReader which had a meaningful definition and hence couldn't be optimized away.

(1)注:我不是说了JITer这样做,只是如果删除的方法,那就需要做某种形式的的检查。

(1) Note: I'm not saying the JITer does this, just that if it removed the method it would need to do some form of null checking.