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?