.Net 下區(qū)別使用 ByRef/ByVal 的重要性
發(fā)表時(shí)間:2024-02-13 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
一直以來在 VB6 下,參數(shù)默認(rèn)都是按照 ByRef 傳送的,(即按地址傳送) 而在 .Net(C#,VB.Net) 下, 參數(shù)默認(rèn)是使用 ByVal (即按值傳送) 傳送的,一直沒怎么注意。
這些天在優(yōu)化程序時(shí)發(fā)現(xiàn) 當(dāng)傳送 大變量時(shí),使用默認(rèn)方式(ByVal) 效率相當(dāng)?shù)?/p>
如傳入的參數(shù)變量類型 是 大字符串,數(shù)組,集合,DataSet 等
測(cè)試的關(guān)鍵代碼如下,我傳入的字符串并沒有特別大,變量越大,使用 ByRef 效率越高,當(dāng)然,當(dāng)傳入得變量可以被修改或無其他作用時(shí),可以改用 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