和VB.Net 中不同,VB6 中默认是使用 ByRef 来传递参数了,看来似乎没有什么可以优化得地方。
可是,实际上 如果你调用 API 得话,从 API浏览器复制下来得代码却是 强制使用 ByVal 传参得这就给了我们优化得机会。
我又重新使用该代码 分别测试了一下 ByRef ,ByVal 得区别,结果很振奋: ByRef 比 ByVal 提高了140倍,ByRef 比 ByVal 提高了89倍。
代码如下,插入ComboBox 得字符串越长,越能显示 ByRef 得威力。
新建From1(窗体),新建Command1(按钮CommandButton),Combo1(ComboBox)代码:
Option Explicit
Private Declare Function SendMessageByRef Lib "user32" Alias "SendMessageA" (ByRef hWnd As Long, ByRef wMsg As Long, ByRef wParam As Long, ByRef lParam As Any) As Long
Private Declare Function SendMessageByVal Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Any) As Long
Private Declare Function GetTickCount Lib "kernel32" () As Long
Private Const CB_ADDSTRING = &H143
Private Sub Command1_Click()
Dim i As Long
Dim t As Long
Dim s As String
s = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
Combo1.Clear
t = GetTickCount()
'使用API ByRef
For i = 1 To 10000
SendMessageByRef Combo1.hWnd, CB_ADDSTRING, 0, s
Next
Debug.Print "ByRef " & GetTickCount - t
Combo1.Clear
t = GetTickCount()
'使用API ByVal
For i = 1 To 10000
SendMessageByVal Combo1.hWnd, CB_ADDSTRING, 0, s
Next
Debug.Print "ByVal " & GetTickCount - t
Combo1.Clear
t = GetTickCount()
'使用普通 ComboBox Add
For i = 1 To 10000
Combo1.AddItem s
Next
Debug.Print "ComboBox Add " & GetTickCount - t
MsgBox "完成"
End Sub
运行结果:
ByRef 31
ByVal 4359
ComboBox Add 2766
差距很大。