.Net 下区别使用 ByRef/ByVal 的重要性 分享
编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
这篇文章介绍了.Net 下区别使用 ByRef/ByVal 的重要性,有需要的朋友可以参考一下
一直以来在 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
而在 .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