一直以來在 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
新聞熱點
疑難解答
圖片精選