Does javascript use immutable or mutable strings? Do I need a "string builder"?
|
from the rhino book:
|
|||||||
|
They are immutable. 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...
Here are performance speed tests. All three of them create a gigantic string made up of concatenating I've created three types of tests
Then I created the same three tests by abstracting them into Here are some numbers from Feb 21, 2013, if you don't want to follow the link. The number on each test is in operations/second (higher is better)
Findings
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, thanks for the input Roy. |
|||||||||||||||||
|
Performance tip: No StringBuilder in javascript. |
|||||||||||||||
|
JavaScript strings are indeed immutable. |
|||||
|
Strings in Javascript are immutable |
|||
|
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. |
|||
|