Problems needing attention in string stitching in JavaScript _javascript tips

Source: Internet
Author: User
In the development of everyone will also pay attention to the use of StringBuilder as far as possible without the use of ordinary string concatenation. But perhaps most developers are ignoring the need to pay attention to this efficiency problem in JS.
Here is a performance test to speak with the facts!
Copy Code code 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 ("string concatenation method Time consuming:" + (D2.gettime ()-d1.gettime ()) + "milliseconds;");
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 ("Array mode time consuming:" + (D2.gettime ()-d1.gettime ()) + "milliseconds;");
}
Using the string concatenation function implemented by array, it is convenient for the C # developer to specifically name Stringbuilde to facilitate understanding
function StringBuilder () {
This._strings_=new Array;
}
Stringbuilder.prototype.append=function (str) {
This._strings_.push (str);
};
Stringbuilder.prototype.tostring=function () {
Return This._strings_.join ("");
};

The result of the three execution of the Xntest () function is:

string concatenation takes time: 735 milliseconds; array mode is time-consuming: 62 milliseconds;
string concatenation takes time: 766 milliseconds; array mode is time-consuming: 63 milliseconds;
string concatenation takes time: 703 milliseconds; array mode is time-consuming: 63 milliseconds;

This example is stitching 10,000 times string performance test, I believe that the results are obvious to all, interested friends can test their own.
Therefore, in the foreground development we should also try to avoid large-scale string concatenation operation, should use the array method to reasonably improve the 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.