Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ByRef vs ByVal performance when passing strings

Reading Which is faster? ByVal or ByRef? made me wonder whether the comments in there did apply to Strings in terms of performance. Since strings are copied before being passed, isn't it much more efficient (if the callee doesn't need a copy of string course) to pass strings ByRef?

Thanks,
CFP.

Edit: Consider this code, which made me think there was some kind of copy going on:

Sub Main()
    Dim ByValStr As String = "Hello World (ByVal)!"
    Dim ByRefStr As String = "Hello World (ByRef)!"

    fooval(ByValStr)
    fooref(ByRefStr)

    Console.WriteLine("ByVal: " & ByValStr)
    Console.WriteLine("ByRef: " & ByRefStr)

    Console.ReadLine()
End Sub


Sub fooval(ByVal Str As String)
    Str = "foobar"
End Sub

Sub fooref(ByRef Str As String)
    Str = "foobar"
End Sub

It outputs:

ByVal: Hello World (ByVal)!
ByRef: foobar
like image 459
Clément Avatar asked Dec 17 '22 23:12

Clément


1 Answers

Strings are not copied before being passed. Strings are reference types, even though they behave somewhat like value types.

You should use whatever makes the most sense in the context of your requirements. (And if your requirements happen to be something like "must squeeze every last nanosecond of performance at the expense of all other considerations" then you should probably crack out the profiler rather than asking on stackoverflow!)

This is almost certainly something that you don't need to worry about, and I doubt if there's ever a significant performance difference. The only situation where I can see any chance of a difference would be when passing big value types.

like image 150
LukeH Avatar answered Dec 29 '22 19:12

LukeH