JavaScript learning notes 2 String concatenation _ basic knowledge

Source: Internet
Author: User
Tags javascript string concatenation
Some knowledge points of JavaScript String concatenation are worth looking at to improve efficiency. Var str = "hello ";
Str + = "world ";
In fact, the steps behind the scenes are as follows:
(1) create a string that stores "hello.
(2) create a string for storing "world.
(3) create a string that stores the connection results.
(4) copy the current content of str to the result.
(5) Copy "world" to the result.
(6) Update str to point it to the result.
Each time the string connection is completed, steps 2 to 6 are executed, which consumes a lot of resources. If you repeat this process several hundred or even thousands of times, it will cause performance problems. The solution is to use an Array object to store strings, and then use the join () method (the parameter is a Null String) to create the final string. Imagine Replacing the previous code with the following code:

The Code is as follows:


Var str = new Array ();
Str [0] = "hello ";
Str [1] = "world ";
Str. join ("");


In this way, no matter how many strings are introduced in the array, the join operation occurs only when the join () method is called. The procedure is as follows:
(1) create a string for storing the result.
(2) copy each string to a proper position in the result.

The Code is as follows:


Function StringBuilder (){
This. _ string = new Array ();
}
StringBuilder. prototype. Append = function (str ){
This. _ string. push (str );
}
StringBuilder. prototype. toString = function (){
Return this. _ string. join ("");
}


Articles on efficiency improvement:
The fastest way to splice html array strings

StringBuffer class connected to large strings in javascript

For more information, refer to the articles in the past.

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.