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! CopyCode The 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.

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.