JavaScript uses the StringBuffer class to improve the efficiency of + = concatenating strings

Source: Internet
Author: User

Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> </title>
</Head>
<Body>
</Body>
<Script type = "text/javascript"> <! --
Var str = 'hello ';
Str + = 'World ';
// Steps 2 to 6 are performed each time the string connection is completed.
// In fact, the steps behind the scenes are as follows:
/**//*
1. Create a string for storing 'hello'
2. Create a string for storing 'World'
3. Create a string that stores the link result
4. Copy the current content of str to the result.
5. Copy 'World' to the result.
6. Update str to point it to the result
*/

// To improve the performance, it is best to concatenate strings using arrays.
// Create a StringBuffer class
Function StringBuffer (){
This. _ strings _ = [];
};
StringBuffer. prototype. append = function (str ){
This. _ strings _. push (str );
};
StringBuffer. prototype. toString = function (){
Return this. _ strings _. join ('');
};

// Call the StringBuffer class to concatenate strings
// Step 2 is performed each time string connection is completed
// In fact, the steps behind the scenes are as follows:
/**//*
1. Create a string for storing results
2. copy each string to a proper position in the result.
*/
Var buffer = new StringBuffer ();
Buffer. append ('hello ');
Buffer. append ('World ');
Var result = buffer. toString ();

// Use StringBuffer for analogy + = save 50% ~ 66% of the time
// -->
</Script>
</Html>

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.