Reputation: 11399
Can somebody explain how it can be that the same API call returns so much quicker with VB6 than with VB.NET?
Here is my VB6 code:
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
And here is my VB.NET code:
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)
I ran each version 1000 times.
The VB6 version needed 2.04893359351538 ms. The VB.NET version needed 372.1322491699365 ms.
Both Release and Debug version are about the same.
What is happening here?
Upvotes: 3
Views: 1032
Reputation: 19335
Do not use the *A version, just skip the suffix, and use StringBuilder instead of 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)
Upvotes: 7