JavaScript string connection Performance Optimization

Source: Internet
Author: User

Copy codeThe Code is as follows:
Var str = "hello ";
Str + = "world ";

Background work:
1) create a string that stores "hello" and point str to it.
2) create a string for storing "world.
3) create a string for storing the result.
4) copy the current content in str to the result string.
5) Copy world to the result string.
6) Update str to point str to the result string.
Repeat each concatenated string. 2 )~ 6) if you repeat hundreds of times, it will consume a lot of resources and affect performance.
Solution:
Use the Array object to store strings, and then use the join () method to output the results.
This is similar to the StringBuffer class in Java.
Copy codeThe Code is as follows:
Function StringBuffer (){
This. _ strings = new Array;
}
StringBuffer. prototype. append = function (str ){
This. _ strings. push (str );
}
StringBuffer. prototype. toString = function (){
Return this. _ strings. join ("");
}

Test performance:
Code 1: concatenate a string using "+ ="
Copy codeThe Code is as follows:
Var d = new Date ();
Var str = "";
For (var I = 0; I <10000; I ++ ){
Str + = "test ";
}
Var d2 = new Date ();
Document. writeln (d2.getTime ()-d. getTime ());

Code 2: Use StringBuffer
Copy codeThe Code is as follows:
Var d = new Date ();
Var str = new StringBuffer ();
For (var I = 0; I <10000; I ++ ){
Str. append ("test ");
}
Var res = str. toString ();
Var d2 = new Date ();
Document. writeln (d2.getTime ()-d. getTime ());

From the results of Multiple tests, StringBuffer can save more than 50% of the time.

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.