views:

2088

answers:

5

does javascript use immutable or mutable strings?

+1  A: 

JavaScript strings are indeed immutable.

JC Grubbs
Doc link? I can't find any specifics on this.
DevelopingChris
+1  A: 

Strings in Javascript are immutable

Glenn Slaven
+13  A: 

from the rhino book:

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it[1]

minty
docgnome
Thanks, I didn't know that.
Braveyard
+5  A: 

Performance tip:
If you have to concatenate large strings, put the string parts into an array and use the Array.Join() method to get the overall string. This can be many times faster for concatenating a large number of strings.

No StringBuilder in javascript.

Ash
I know there isn't a stringBuilder, msAjax has one, and I was just pondering whether or not its useful
DevelopingChris
What does this have to do with strings being immutable or not?
docgnome
+1  A: 

Regarding your question (in your comment to Ash's response) about the StringBuilder in ASP.NET Ajax the experts seem to disagree on this one.

Christian Wenz says in his book Programming ASP.NET AJAX (O'Reilly) that "this approach does not have any measurable effect on memory (in fact, the implementation seems to be a tick slower than the standard approach)."

On the other hand Gallo et al say in their book ASP.NET AJAX in Action (Manning) that "When the number of strings to concatenate is larger, the string builder becomes an essential object to avoid huge performance drops."

I guess you'd need to do your own benchmarking and results might differ between browsers, too. However, even if it doesn't improve performance it might still be considered "useful" for programmers who are used to coding with StringBuilders in languages like C# or Java.

BirgerH