Re: Javascript String Concatenations
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: Javascript String Concatenations

From: Lasse Reichstein Nielsen <lrn@hotpop.com>
Date: Wed Nov 30 2005 - 19:27:35 CET

psimakov@outplay.com writes:

> Here is test study that shows dramatic performance impact of String
> Concatenations and how to avoid it.
>
> http://www.softwaresecretweapons.com/jspwiki/Wiki.jsp?page=JavascriptStringConcatenation

The author hints at the better solution, but doesn't elaborate.
In Javascript, a simple array can take the place of the Java StringBuffer,
so each "append" is a "push" and the "toString" is "join", i.e.,

 var buf = [];
 for(...long loop...) {
   buf.push("string to append");
 }
 ... buf.join("");

You can also try to hide this in a StringBuffer-like object:

---
 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("");
 };
 alert(new StringBuffer().append("hello ").append("world"));
---
It is so simple that there is no reason *not* to go for the general
solution instead of the stopgap measure of intermediate buffers
(ofcourse, if you know the size of your data, you can check that
intermediate buffers will do, but the time complexity is still
quadratic in the size of the outer loop - it's just the constant
that got smaller).
/L
-- 
Lasse Reichstein Nielsen  -  lrn@hotpop.com
 DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
  'Faith without judgement merely degrades the spirit divine.'
Received on Sat Dec 3 04:33:48 2005