JavaScript String Connectivity performance optimization _javascript tips

Source: Internet
Author: User
Copy Code code as follows:

var str = "Hello";
str = "World";

Work in the background:
1 creates a string that stores "Hello" and causes Str to point to it.
2 Create a string that stores "world".
3 Create a string that stores the results.
4 Copy the current content in Str to the result string.
5 Copy the world into the result string.
6 Update str so that STR points to the result string.
Each stitch string repeats 2 ~6), and if repeated hundreds of times it consumes resources and affects performance.
Workaround:
Use the Array object to store the string, and then use the join () method to output the result.
Modeled after the StringBuffer class in Java.
Copy Code code 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: Concatenation of strings with "+ ="
Copy Code code 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: Using StringBuffer
Copy Code code 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 multiple test results, the use of StringBuffer can save more than 50% of the time.

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.