3

有人能解释一下为什么使用 VB6 比使用 VB.NET 更快地返回相同的 API 调用吗?

这是我的VB6代码:

Public Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long


Public Function GetWindowTextEx(ByVal uHwnd As Long) As String

Dim lLen&
lLen = GetWindowTextLength(uHwnd) + 1

Dim sTemp$
sTemp = Space(lLen)

lLen = GetWindowText(uHwnd, sTemp, lLen)

Dim sRes$
sRes = Left(sTemp, lLen)

GetWindowTextEx = sRes

End Function

这是我的 VB.NET 代码:

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Integer, ByVal lpWindowText As String, ByVal cch As Integer) As Integer

    Dim sText As String = Space(Int16.MaxValue)
    GetWindowText(hwnd, sText, Int16.MaxValue)

我运行每个版本 1000 次。

VB6 版本需要 2.04893359351538 毫秒。VB.NET 版本需要 372.1322491699365 毫秒。

Release 和 Debug 版本都差不多。

这里发生了什么?

4

1 回答 1

7

不要使用 *A 版本,只是跳过后缀,使用 StringBuilder 代替 String:

Private Declare Auto Function GetWindowText Lib "user32" (ByVal hwnd As Integer, ByVal lpWindowText As StringBuilder, ByVal cch As Integer) As Integer
Private Declare Function GetWindowTextLength Lib "user32" (ByVal hwnd As Integer) As Integer

Dim len As Integer = GetWindowTextLength (hwnd)
Dim str As StringBuilder = new StringBuilder (len)
GetWindowText (hwnd, str, str.Capacity)
于 2012-11-06T22:48:01.540 回答