The importance of using byref/byval differently under. Net

Source: Internet
Author: User
Difference

All along, in VB6, parameters are routed by ByRef (that is, delivered by address).

Under. Net (c#,vb.net), parameters are routed by default using ByVal (that is, by value) and have not been noticed.

These days the optimizer found that using the default method (ByVal) is quite inefficient when transferring large variables

such as the incoming parameter variable type is a large string, array, collection, DataSet, etc.

The key code of the test is as follows, the string I passed in is not particularly large, the larger the variable, the higher the use of byref, of course, when the incoming variable can be modified or no other effect, you can switch to 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




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.