↑
Main Page
traditional string concatenation
StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
return this.__strings__.join(“”);
};
The first thing to note about this code is the
strings
property, which is intended to be private. It has
only two methods:
append()
and
toString()
. The
append()
method takes an argument and appends
it to the strings array and the
toString()
method returns the actual concatenated string by using the
array’s
join()
method. To concatenate a group of strings using a
StringBuffer
object, use the follow-
ing code:
var buffer = new StringBuffer();
buffer.append(“hello “);
buffer.append(“world”);
var result = buffer.toString();
You can test the performance of the
StringBuffer
object versus traditional string concatenation with
the following code:
var d1 = new Date();
var str = “”;
for (var i=0; i < 10000; i++) {
str += “text”;
}
var d2 = new Date();
document.write(“Concatenation with plus: “ + (d2.getTime() - d1.getTime()) + “
milliseconds”);
var oBuffer = new StringBuffer();
d1 = new Date();
for (var i=0; i < 10000; i++) {
oBuffer.append(“text”);
}
var sResult = buffer.toString();
d2 = new Date();
document.write(“<br />Concatenation with StringBuffer: “ + (d2.getTime() -
d1.getTime()) + “ milliseconds”);
The code runs two tests on string concatenation, the first by using the additive operator and the second
by using the
StringBuffer
. Each operation concatenates 10,000 strings. The dates
d1
and
d2
are used
to determine how much time it takes to complete the operation. Remember, when you create a new
Date
object without any arguments, it is assigned current date and time. To figure out how much time elapsed
during the concatenation, the millisecond representation of the dates (returned by the
getTime()
method) are subtracted. This is a common method of measuring JavaScript performance. The results of
this test should show a savings of 100–200% over using the additive operator.
98
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 98
Free JavaScript Editor
Ajax Editor
©
→