Does javascript use immutable or mutable strings? Do I need a "string builder"?
-
5Yes, the y are immutable and you need a "string builder" of some sort. Read this blog.codeeffects.com/Article/String-Builder-In-Java-Script or this codeproject.com/KB/scripting/stringbuilder.aspx– KizzJul 14, 2011 at 20:14
-
4Interesting, those examples contradict my findings in my answer.– Ruan MendesFeb 23, 2012 at 19:29
10 Answers
They are immutable. You cannot change a character within a string with something like var myString = "abbdef"; myString[2] = 'c'
. The string manipulation methods such as trim
, slice
return new strings.
In the same way, if you have two references to the same string, modifying one doesn't affect the other
let a = b = "hello";
a = a + " world";
// b is not affected
However, I've always heard what Ash mentioned in his answer (that using Array.join is faster for concatenation) so I wanted to test out the different methods of concatenating strings and abstracting the fastest way into a StringBuilder. I wrote some tests to see if this is true (it isn't!).
This was what I believed would be the fastest way, though I kept thinking that adding a method call may make it slower...
function StringBuilder() {
this._array = [];
this._index = 0;
}
StringBuilder.prototype.append = function (str) {
this._array[this._index] = str;
this._index++;
}
StringBuilder.prototype.toString = function () {
return this._array.join('');
}
Here are performance speed tests. All three of them create a gigantic string made up of concatenating "Hello diggity dog"
one hundred thousand times into an empty string.
I've created three types of tests
- Using
Array.push
andArray.join
- Using Array indexing to avoid
Array.push
, then usingArray.join
- Straight string concatenation
Then I created the same three tests by abstracting them into StringBuilderConcat
, StringBuilderArrayPush
and StringBuilderArrayIndex
http://jsperf.com/string-concat-without-sringbuilder/5 Please go there and run tests so we can get a nice sample. Note that I fixed a small bug, so the data for the tests got wiped, I will update the table once there's enough performance data. Go to http://jsperf.com/string-concat-without-sringbuilder/5 for the old data table.
Here are some numbers (Latest update in Ma5rch 2018), if you don't want to follow the link. The number on each test is in 1000 operations/second (higher is better)
Browser | Index | Push | Concat | SBIndex | SBPush | SBConcat |
---|---|---|---|---|---|---|
Chrome 71.0.3578 | 988 | 1006 | 2902 | 963 | 1008 | 2902 |
Firefox 65 | 1979 | 1902 | 2197 | 1917 | 1873 | 1953 |
Edge | 593 | 373 | 952 | 361 | 415 | 444 |
Exploder 11 | 655 | 532 | 761 | 537 | 567 | 387 |
Opera 58.0.3135 | 1135 | 1200 | 4357 | 1137 | 1188 | 4294 |
Findings
Nowadays, all evergreen browsers handle string concatenation well.
Array.join
only helps IE 11Overall, Opera is fastest, 4 times as fast as Array.join
Firefox is second and
Array.join
is only slightly slower in FF but considerably slower (3x) in Chrome.Chrome is third but string concat is 3 times faster than Array.join
Creating a StringBuilder seems to not affect perfomance too much.
Hope somebody else finds this useful
Different Test Case
Since @RoyTinker thought that my test was flawed, I created a new case that doesn't create a big string by concatenating the same string, it uses a different character for each iteration. String concatenation still seemed faster or just as fast. Let's get those tests running.
I suggest everybody should keep thinking of other ways to test this, and feel free to add new links to different test cases below.
-
@Juan, the link you asked us to visit concatenates a 112-char string 30 times. Here's another test that might help balance things - Array.join vs string concatenation on 20,000 different 1-char strings (join is much faster on IE/FF). jsperf.com/join-vs-str-concat-large-array Jul 22, 2013 at 18:03
-
1@RoyTinker Roy, oh Roy, your tests are cheating because you're creating the array in the setup of the test. Here's the real test using different characters jsperf.com/string-concat-without-sringbuilder/7 Feel free to create new test cases, but creating the array is part of the test itself Jul 22, 2013 at 18:11
-
2@RoyTinker Yes it is, any string builder will require building the array. The question is about whether a string builder is needed. If you already have the strings in an array, then it is not a valid test case for what we're discussing here Jul 22, 2013 at 18:20
-
1@JuanMendes - Ok, point taken. My test assumes the array already exists, which you can't assume when evaluating string builders. Jul 22, 2013 at 18:22
-
1
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
-
7
-
141The Rhino book quote (and thus this answer) is wrong here. In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside
null
undefined
number
andboolean
. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string"hello"
to be"world"
is like deciding that from now on the number 3 is the number 4... it makes no sense. Sep 16, 2013 at 22:20 -
11Yes, like my comment says strings are immutable, but they are not reference types nor they are objects - they are primitive value types. An easy way to see they're neither would be to try to add a property to a string and then read it:
var a = "hello";var b=a;a.x=5;console.log(a.x,b.x);
Sep 17, 2013 at 16:08 -
11@VidarS.Ramdal No,
String
objects created using the string constructor are wrappers around JavaScript string values. You can access the string value of the boxed type using the.valueOf()
function - this is also true forNumber
objects and number values. It's important to noteString
objects created usingnew String
are not actual strings but are wrappers or boxes around strings. See es5.github.io/#x15.5.2.1 . About how things convert to objects see es5.github.io/#x9.9 Feb 21, 2014 at 13:43 -
8As for why some people say strings are objects, they are probably coming from Python or Lisp or any other language where its spec use the word "object" to mean any kind of datum (even integers). They just need to read how the ECMA spec defines the word: "member of the type Object". Also, even the word "value" may mean different things according to specs of different languages. Apr 2, 2014 at 21:28
Just to clarify for simple minds like mine (from MDN):
Immutables are the objects whose state cannot be changed once the object is created.
String and Numbers are Immutable.
Immutable means that:
You can make a variable name point to a new value, but the previous value is still held in memory. Hence the need for garbage collection.
var immutableString = "Hello";
// In the above code, a new object with string value is created.
immutableString = immutableString + "World";
// We are now appending "World" to the existing value.
This looks like we're mutating the string 'immutableString', but we're not. Instead:
On appending the "immutableString" with a string value, following events occur:
- Existing value of "immutableString" is retrieved
- "World" is appended to the existing value of "immutableString"
- The resultant value is then allocated to a new block of memory
- "immutableString" object now points to the newly created memory space
- Previously created memory space is now available for garbage collection.
-
Would be the same if you do
var immutableString = "Hello"; immutableString="world"
? I mean assign a totally new value to the variable– user6791921Sep 7, 2021 at 1:47 -
-
thanks katinka but what I mean, would you be "mutating the string" if you assign a totally new value? Or applies the same you explained so well here? If It appears you are mutating it, but you´re not...– user6791921Sep 7, 2021 at 16:15
-
3You're replacing it with a new memory field. The old string gets discarded. Sep 9, 2021 at 14:48
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.
There is no StringBuilder
in JavaScript.
-
I know there isn't a stringBuilder, msAjax has one, and I was just pondering whether or not its useful Sep 9, 2008 at 3:56
-
7
-
4@docgnome: Because strings are immutable, string concatenation requires creating more objects than the Array.join approach Jan 17, 2011 at 20:37
-
9According to Juan's test above, string concatenation is actually faster in both IE and Chrome, while slower in Firefox. Feb 21, 2012 at 18:36
-
10Consider updating your answer, it may have been true a long time ago, but it's not anymore. See jsperf.com/string-concat-without-sringbuilder/5 May 20, 2014 at 16:21
The string type value is immutable, but the String object, which is created by using the String() constructor, is mutable, because it is an object and you can add new properties to it.
> var str = new String("test")
undefined
> str
[String: 'test']
> str.newProp = "some value"
'some value'
> str
{ [String: 'test'] newProp: 'some value' }
Meanwhile, although you can add new properties, you can't change the already existing properties
A screenshot of a test in Chrome console
In conclusion, 1. all string type value (primitive type) is immutable. 2. The String object is mutable, but the string type value (primitive type) it contains is immutable.
-
Javascript String objects are immutable developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures– prasunOct 14, 2015 at 14:28
-
1@prasun but in that page it says: "All types except objects define immutable values (values, which are incapable of being changed). " String objects are object. And how is it immutable if you can add new properties on it? Oct 15, 2015 at 4:18
-
read the section "String Type". The Javascript's String link points to both primitive and Object and later it says "JavaScript strings are immutable". It looks like the document is not clear on this topic as it conflicts at two different notes– prasunOct 15, 2015 at 4:29
-
7
-
2It's very easy to test by running @zhanziyang's code above. You can totally add new properties to a
String
object (wrapper), meaning it is not immutable (by default; like any other object you can callObject.freeze
on it to render it immutable). But a primitive string value type, whether contained in aString
object wrapper or not, is always immutable. Jan 30, 2018 at 16:29
Strings are immutable – they cannot change, we can only ever make new strings.
Example:
var str= "Immutable value"; // it is immutable
var other= statement.slice(2, 10); // new string
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.
It's a late post, but I didn't find a good book quote among the answers.
Here's a definite except from a reliable book:
Strings are immutable in ECMAScript, meaning that once they are created, their values cannot change. To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value... —Professional JavaScript for Web Developers, 3rd Ed., p.43
Now, the answer which quotes Rhino book's excerpt is right about string immutability but wrong saying "Strings are assigned by reference, not by value." (probably they originally meant to put the words an opposite way).
The "reference/value" misconception is clarified in the "Professional JavaScript", chapter named "Primitive and Reference values":
The five primitive types...[are]: Undefined, Null, Boolean, Number, and String. These variables are said to be accessed by value, because you are manipulating the actual value stored in the variable. —Professional JavaScript for Web Developers, 3rd Ed., p.85
that's opposed to objects:
When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference.—Professional JavaScript for Web Developers, 3rd Ed., p.85
-
FWIW: The Rhino book probably means that internally/implementation a string assignment is storing/copying a pointer (rather than copying the contents of the string). It doesn't look like an accident on their part, based on the text after that. But I agree: they misuse the term "by reference". Its not "by reference" just because the implementation passes pointers (for performance). Wiki - evaluation strategy is an interesting read on this topic. Oct 15, 2019 at 17:45
JavaScript strings are indeed immutable.
-
-
1"attempting to set an individual character won't work" -- developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…– KenFeb 27, 2011 at 4:54