Notes for String concatenation in javascript

Source: Internet
Author: User

During development, you will also pay attention to using StringBuilder instead of the common String concatenation method. However, most developers may ignore this efficiency issue in js.
Let's take a performance test and talk about it with facts!
Copy codeThe Code is as follows:
Function xntest (){
Var d1 = new Date ();
Var str = "";
For (var I = 0; I <10000; I ++ ){
Str + = "stext ";
}
Var d2 = new Date ();
Document. write ("Time consumed by String concatenation:" + (d2.getTime ()-d1.getTime () + "millisecond ;");
D1 = new Date ();
Var sb = new StringBuilder ();
For (var I = 0; I <10000; I ++ ){
Sb. append ("stext ");
}
Var result = sb. toString ();
D2 = new Date ();
Document. write ("Time consumed in array mode:" + (d2.getTime ()-d1.getTime () + "millisecond ;");
}
//// Use the String concatenation function implemented by Array to facilitate c # developers to name StringBuilde for ease of understanding
Function StringBuilder (){
This. _ strings _ = new Array;
}
StringBuilder. prototype. append = function (str ){
This. _ strings _. push (str );
};
StringBuilder. prototype. toString = function (){
Return this. _ strings _. join ("");
};

After the xntest () function is executed three times, the result is:

String concatenation time: 735 milliseconds; array time: 62 milliseconds;
String concatenation time: 766 milliseconds; array time: 63 milliseconds;
String concatenation time: 703 milliseconds; array time: 63 milliseconds;

This example is a 10000-time String concatenation performance test. We believe that the results are obvious to all. If you are interested, you can test it on your own.
Therefore, in front-end development, we should also try to avoid large-scale String concatenation operations, and use arrays to reasonably improve code efficiency.

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.