Since strings in JavaScript are basic types, does passing a string to a function create a local copy of it? I'm wondering about this since you can't modify strings after they've been created, so it would seem illogical that JavaScript VMs wouldn't just pass the string's address to the function internally.
If anybody is going to tell me that i shouldn't worry about this (this happens a lot when talking to web developers), I'm working on HTML5 games and garbage collection is a major concern, so i really need to know.
All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.
Strings are Reference/Complex Object Type When you assign a string variable to another variable, It actually copies the reference to the object but not the object itself. It means, since the string variable holds the reference to the actual data, so it passes this reference and not the actual data.
OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not. Show activity on this post. I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function.
Java is officially always pass-by-value. The question is, then, “what is passed by value?” As we have said in class, the actual “value” of any variable on the stack is the actual value for primitive types (int, float, double, etc) or the reference for reference types.
The string will be passed by reference.
A string is not mutable so whenever you try to change it you get a new string (eg. by doing value+="more"
).
Also see: What does immutable mean?
@T.J. Crowder: by value vs by ref - if you are looking at the language definition you are correct. However I don't think there is an implementation that actually creates a copy of the string because it would be incredibly slow. Also since strings are immutable primitives there is no need to copy them since they can't change.
I believe the specification is silent on this point. However, it would be a truly idiotic implementation that passed the actual content of the string rather than passing a reference to that content in memory, even if strings are theoretically "primitives". I suspect most implementations treat "primitive" strings much as they treat object references (in this regard, obviously not in some others, such as ===
), but just not with the Object
trappings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With