The importance of using byref/byval differently under. Net

Source: Internet
Author: User
This article describes the importance of using byref/byval under. Net, and friends who need it can refer to

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

Copy Code code as follows:


 private Declare function GetTickCount Lib "kernel32" () as Int32
    Private function Tes Tbyref (ByRef AA As String) As String
        AA = "1" & AA
  &nbs p;     testbyref = AA
    End Function
    Private function Testbyval (ByVal AA As String) As String
        AA = "1" & AA
  & nbsp;     testbyval = AA
    end Function
    Private Sub Button1_Click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
   & nbsp;    Dim teststr As String
        Dim newstr As String
& nbsp;       Dim t As Int32
        Dim II as Int32
      &NBsp Teststr = "WOSDFSDFDSFDSFSFDSFSFSFSFSFSFDSFDSFCVXCVXCVCXVVCXVVVXVCVXV"
         T = GetTickCount
        for II = 1 to 10000
    &N bsp;       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.