VB.NET: If I pass a String ByVal into a function but do not change the string, do I have one or two strings in memory?

Rob Sobers picture Rob Sobers · Jun 26, 2009 · Viewed 11k times · Source

I know strings are immutable, so the minute you change a string reference's value .NET makes a brand new string on the heap.

But what if you don't change the value of a string reference; rather, you simply pass it into a function ByVal -- does this operation copy the string value on the heap as well? My inclination is "no," but I'd like to confirm.

For example:

Public Function IsStringHello(ByVal test As String) As Boolean 
  Return (String.Compare(test, "Hello") = 0)    
End Function

Calling program:

Dim myWord as String = "Blah"
Dim matchesHello as Boolean = IsStringHello(myWord)

I know passing myWord by value makes a copy of the reference to "Blah", but since I have not tried to change the string itself, would it make another copy of the string on the heap?

Answer

Konrad Rudolph picture Konrad Rudolph · Jun 26, 2009

By the way, string interning is completely unrelated to that. The rule for passing parameters to functions is the same for all reference types (and really, all types), no matter how they are managed internally.

The rule is simple and you have stated it correctly: pass by value copies the reference, not the target. No heap space is copied here.