VB.NET中的API调用比VB6慢得多

时间:2012-11-06 19:36:07

标签: vb.net performance vb6

有人可以解释一下,使用VB6,相同的API调用返回的速度比使用VB.NET快得多吗?

这是我的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 ms。 VB.NET版本需要372.1322491699365 ms。

Release和Debug版本大致相同。

这里发生了什么?

1 个答案:

答案 0 :(得分: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)