Alexander Abramovich
Alexander Abramovich

Reputation: 11438

JavaScript VM optimization on strings concatenation

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

Answers (3)

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

A number of points:

  • What you cite was never a performance problem in Java; the compiler always optimized it using StringBuffer. Problems only arise when appending to a variable in a loop.
  • Java and JavaScript have absolutely nothing to do with each other.
  • The JavaScript runtime would have to work very hard to de-optimize the issue until it takes milliseconds. On a modern CPU, a millisecond is an eternity.
  • Premature optimization. Don't.
  • Profile/Benchmark before you optimize. Here's numbers from someone who did, but note that the results are 3 years old and thus meaningless.

Upvotes: 0

Sergio Moura
Sergio Moura

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());

Source: http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/72429b15-73e2-4b4e-9288-9e1dfd47858b/

Upvotes: 0

Šime Vidas
Šime Vidas

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

Related Questions