Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 889
Rob Sobers Avatar asked Jun 26 '09 18:06

Rob Sobers


1 Answers

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.

like image 91
Konrad Rudolph Avatar answered Sep 20 '22 13:09

Konrad Rudolph