Does javascript use immutable or mutable strings? Do I need a “string builder”?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 astrim,slicereturn new strings.In the same way, if you have two references to the same string, modifying one doesn’t affect the other
Myth Debunking – String concatenation is NOT slow
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, avoiding push and using an array to store the strings to then join them in the end.
Some benchmarks
I’ve created two types of tests
Array.push, then usingArray.joinFor each of those tests, I looped appending a constant value and a random string;
Findings
Nowadays, all evergreen browsers handle string concatenation better, at least twice as fast.
i-12600k (added by Alexander Nenashev)
Chrome/117
Firefox/118
Results below on a 2.4 GHz 8-Core i9 Mac on Oct 2023
Chrome
Firefox
Brave
Safari
Opera