一直以來在 VB6 下,參數默認都是按照 ByRef 傳送的,(即按地址傳送)
而在 .Net(C#,VB.Net) 下, 參數默認是使用 ByVal (即按值傳送) 傳送的,一直沒怎麼注意。
這些天在優化程序時發現 當傳送 大變量時,使用默認方式(ByVal) 效率相當低
如傳入的參數變量類型 是 大字符串,數組,集合,DataSet 等
測試的關鍵代碼如下,我傳入的字符串並沒有特別大,變量越大,使用 ByRef 效率越高,當然,當傳入得變量可以被修改或無其他作用時,可以改用 ByRef 傳
復制代碼 代碼如下:
Private Declare Function GetTickCount Lib "kernel32" () As Int32
Private Function TestByRef(ByRef aa As String) As String
aa = "1" & aa
TestByRef = aa
End Function
Private Function TestByVal(ByVal aa As String) As String
aa = "1" & aa
TestByVal = aa
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim teststr As String
Dim Newstr As String
Dim t As Int32
Dim II As Int32
teststr = "wosdfsdfdsfdsfsfdsfsfsfsfsfsfdsfdsfcvxcvxcvcxvvcxvvvxvcvxv"
t = GetTickCount
For II = 1 To 10000
Newstr = TestByRef(teststr)
Next
MsgBox("ByRef " & CStr(GetTickCount - t))
t = GetTickCount
For II = 1 To 10000
Newstr = TestByVal(teststr)
Next
MsgBox("ByVal " & CStr(GetTickCount - t))
End Sub