JavaScripTools Manual


The StringBuffer class

In JavaScript (as well as in Java), string objects are immutable. This means that, whenever a string operation is performed, a new string is created.

The problem is that if we have a lot of string concatenations, we will produce many string objects that will only consume time (for allocation) and memory (until it is garbage collected - removed from memory). If we concatenate "a" + "b", a new string, "ab" is created, and both "a" and "b" will exist for some time.

The StringBuffer class tries to minimize this effort. It is not possible to create on JavaScript an optimal StringBuffer because of it's data types (we cannot create a low-lever char[]), but the performance is much better than normal string concatenation.

One of the big changes from JavaScripTools 1.X to 2.X was the use of a StringBuffer to build the HTML code for the JavaScripTable. The result? With lots of rows on Internet Explorer, it took more than 1 minute to build the table. On JavaScripTools 2, a few seconds are enough (imagine if we could use those low level optimizations :-).

But, one thing is true - for most cases, specially on a web page, there will be no noticeable performance difference between using a StringBuffer or concatenating the strings directly. It's up to you to determine if a operation is worth using a StringBuffer or not.

Here are some examples:
var sb = new StringBuffer();
sb.toString() -> "OneTwoThree"
sb.length() -> 11
sb.append("A").append("B").append("C") -> The append returns the StringBuffer itself, so it can be nested

The Map class
Table of Contents Next:
Introduction to Parsers