Javascript: Use the stringbuffer class to increase the + = String concatenation Efficiency
Source: Internet
Author: User
1 <! Doctype HTML public " -// W3C // dtd xhtml 1.0 transitional // en " " Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >
2 < HTML xmlns = " Http://www.w3.org/1999/xhtml " >
3 < Head >
4 < Meta HTTP - Equiv = " Content-Type " Content = " Text/html; charset = UTF-8 " / >
5 < Title > < / Title>
6 < / Head>
7 < Body >
8 < / Body>
9 < Script Type = " Text/JavaScript " > <! --
10 VaR Str = ' Hello ' ;
11 Str + = ' World ' ;
12 // Steps 2 to 6 are performed each time the string connection is completed.
13 // In factCodeFollow these steps:
14 /*
15 1. Create a string for storing 'hello'
16 2. Create a string for storing 'World'
17 3. Create a string that stores the link result
18 4. Copy the current content of STR to the result.
19 5. Copy 'World' to the result.
20 6. Update STR to point it to the result
21 */
22
23 // To improve performance, it is best to concatenate strings using arrays.
24 // Create a stringbuffer class
25 Function Stringbuffer () {
26This. _ Strings __=[];
27} ;
28 Stringbuffer. Prototype. append = Function (STR) {
29This. _ Strings _. Push (STR );
30} ;
31 Stringbuffer. Prototype. tostring = Function () {
32Return This. _ Strings _. Join ('');
33} ;
34
35 // Call the stringbuffer class to concatenate strings.
36 // Step 2 is performed each time the string connection is completed.
37 // In fact, the steps behind the scenes are as follows:
38 /*
391. Create a string for storing results
402. copy each string to a proper position in the result.
41*/
42 VaR Buffer = New Stringbuffer ();
43 Buffer. append ( ' Hello ' );
44 Buffer. append ( ' World ' );
45 VaR Result = Buffer. tostring ();
46
47 // Use stringbuffer for analogy + = save 50% ~ 66% of the time
48 // -->
49 < / SCRIPT>
50 < / HTML>
51
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.