日期:2013-08-18 浏览次数:20457 次
一直以来在 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