Share the importance of using ByRef/ByVal in. Net

Source: Internet
Author: User

For a long time in VB6, parameters are transmitted by ByRef by default, that is, transmitted by address)
In. Net (C #, VB. Net), parameters are transmitted by ByVal (that is, by value) by default.
During the optimization program these days, it is found that the default method (ByVal) is quite inefficient when large variables are transferred.
For example, the input parameter variable types are large strings, arrays, sets, DataSet, etc.
The key code for testing is as follows. The input string is not very large. The larger the variable, the higher the ByRef efficiency. Of course, when the input variable can be modified or has no other function, you can use ByRef to transfer data.
Copy codeThe Code is as follows:
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 button#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.