ByRef vs ByVal performance when passing strings

Clément picture Clément · Jul 22, 2010 · Viewed 14.2k times · Source

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

Answer

LukeH picture LukeH · Jul 22, 2010

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.