A stringbuffer class written in Javascript

Source: Internet
Author: User

Javascript is very slow when processing a large number of characters. Based on some articles on the internet, I wrote a simple stringbuffer class:

 

I. Class diagram:

Stringbuffer ()
Stringbuffer (string)
. Append (string)
. Tostring (separator)

 

Ii. Source Code(Only the main method is displayed. You can add other methods by yourself. For the method name, 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); // The following compatibility is better and the speed is faster (tested in IE6)
This. _ buffer [This. _ buffer. Length] = string;
}
Return this;
};
Stringbuffer. Prototype. tostring = function (separator ){
Return this. _ buffer. Join (separator | "");
};

Iii. Usage:
VaR sb = new stringbuffer ("");
SB. append ("B"). append ("C"). append ("D"); // This usage is like in Java
For (VAR I = 0; I <10000; I ++ ){
SB. append (I );
}
Document. Write (sb. tostring ());

4. Compare the generation speed with the normal method
VaR St, et;

St = new date ();
VaR sb = new stringbuffer ("");
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 ("using the stringbuffer class to process 10000 characters added up consumption" + (ET-St) + "millisecond ");
Document. Write ("<br/> <HR> <br/> ");

St = new date ();
VaR S = ""
S + = "";
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 ("using a common method to process 10000 characters in addition consumes" + (ET-St) + "millisecond ");

Click to download the file (right-click the file in the browser/directory to download the file and remove the. jpg suffix)

 

Why is it an image?

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.