JavaScript can be very slow to perform a large number of character processing. Refer to some articles on the Web and write a simple StringBuffer class:
First, class diagram:
StringBuffer ()
StringBuffer (String)
. Append (String)
. toString (separator)
Second, the source code (only show the Main method, others can add their own, method name can refer to the naming method in Java):
function StringBuffer (string) {
This._buffer = [];
This.append (string);
}
StringBuffer.prototype.append = function (string) {
if (string) {
This._buffer.push (string); Use the following compatibility better and faster (IE6 under test)
This._buffer[this._buffer.length] = string;
}
return this;
};
StringBuffer.prototype.toString = function (separator) {
return This._buffer.join (Separator | | "");
};
Third, use:
var sb = new StringBuffer ("a");
Sb.append ("B"). Append ("C"). Append ("D"); This usage is very much like the usage in Java
for (var i = 0; i < 10000; i++) {
Sb.append (i);
}
document.write (Sb.tostring ());
Compare the speed generated by common method
var St, et;
st = new Date ();
var sb = new StringBuffer ("a");
Sb.append ("B"). Append ("C"). Append ("D");
for (var i = 0; i < 10000; i++) {
Sb.append (i);
}
document.write (Sb.tostring ());
ET = new Date ();
document.write ("<br/>");
document.write ("Add 10,000 characters with StringBuffer class and consume" + (et-st) + "milliseconds");
document.write ("<br/>
st = new Date ();
var s = ""
S + + "a";
s + + "B";
s + + "C";
S + + "D";
for (var i = 0; i < 10000; i++) {
s + = i;
}
document.write (s);
ET = new Date ();
document.write ("<br/>");
document.write ("10,000 characters are consumed by the common method +" + (et-st) + "milliseconds");
Click to download (please use the right mouse button/directory Save as, download the. jpg suffix name removed)
Why the download address is a picture.