Reputation: 11438
Some time ago declarations like the following were defined by poor performance:
var a = "my" +
"very" +
"very" +
"long" +
"string" +
"and" +
"even" +
"longer";
I was told that every subsequent +
operation causes an additional string to be created since they are immutable. At least, once that was an issue in Java programming language (mind StringBuffer
vs. String
).
I am talking about the more-or-less recent versions of the browsers of course.
The question is about JavaScript now: is it still not recommended or the runtime can squack (or should I say optimize) the issue like one above in milliseconds without any performance overhead?
Upvotes: 1
Views: 118
Reputation: 346260
A number of points:
StringBuffer
. Problems only arise when appending to a variable in a loop.Upvotes: 0
Reputation: 4942
I just found a simple implementation of the StringBuffer behaviour using JavaScript:
function StringBuffer() {
this.buffer = [];
}
StringBuffer.prototype.append = function append(string) {
this.buffer.push(string);
return this;
};
StringBuffer.prototype.toString = function toString() {
return this.buffer.join("");
};
var buf = new StringBuffer();
buf.append("hello");
buf.append("world");
alert(buf.toString());
Upvotes: 0
Reputation: 185913
This makes more sense if you're concatenating a large amount of string values:
str = [
'string1',
'string2',
'string3',
'string4',
'etc.'
].join( '' );
Upvotes: 2