A StringBuffer class written in JavaScript __java

Source: Internet
Author: User
Tags stringbuffer

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.