You must know some questions about the performance of string concatenation in JavaScript _ basics

Source: Internet
Author: User
Tags stringbuffer

And the core of JavaScript is ECMAScript. Like other languages, ECMAScript strings are immutable, meaning that their values cannot be changed.

Please consider the following code:

Copy Code code as follows:

var str = "Hello";
str = "world"; in fact, the steps that this code performs behind the scenes are as follows:

1. Create a string that stores "Hello".
2. Create a string that stores "world".
3. Create a string that stores the result of the connection.
4. Copy the current contents of STR to the results.
5. Copy "World" into the results.
6. Update Str so that it points to the result.

Each completion of a string connection performs steps 2 through 6, making this operation very resource-intensive. If you repeat this process hundreds of times, or even thousands of times, it can cause performance problems. The workaround is to store the string with the Array object and then create the last string with the Join () method (the argument is an empty string). Imagine replacing the previous code with the following code:

Copy Code code as follows:

var arr = new Array ();
Arr[0] = "Hello";
ARR[1] = "World";
var str = arr.join ("");

In this way, no matter how many strings are introduced in the array, the connection operation occurs only when the join () method is invoked. At this point, the following steps are performed:

1. Create a string that stores the results
2. Copy each string to the appropriate location in the result
Although this solution is good, there are better ways. The problem is that the code does not accurately reflect its intent. To make it easier to understand, you can package the functionality with the StringBuffer class:

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 ("");
};


The first thing to note in this code is the Strings property, which is meant to be private. It has only two methods, namely the Append () and the ToString () method. The append () method has a parameter that attaches the parameter to the string array, and the ToString () method calls the Join method of the array, returning the string that is actually concatenated. To connect a set of strings with a StringBuffer object, you can use the following code:
Copy Code code as follows:

var buffer = new StringBuffer ();
Buffer.append ("Hello");
Buffer.append ("World");
var result = buffer.tostring ();

Based on the above implementation we have to do a run time comparison, that is, "+" one by one string concatenation and the tools we encapsulate. Use the following code to test the performance of the StringBuffer object and the traditional string concatenation method, enter the code in the Chrome console and run:
Copy Code code as follows:

var D1 = new Date ();
var str = "";
for (Var i=0 i < 10000; i++) {
STR + + "text";
}
var d2 = new Date ();

Console.log ("Concatenation with Plus:"
+ (D2.gettime ()-d1.gettime ()) + "milliseconds");

var buffer = new StringBuffer ();
D1 = new Date ();
for (Var i=0 i < 10000; i++) {
Buffer.append ("text");
}
var result = buffer.tostring ();
D2 = new Date ();

Console.log ("Concatenation with StringBuffer:"
+ (D2.gettime ()-d1.gettime ()) + "milliseconds");


This code carries out two tests on string concatenation, the first using the plus sign and the second using the StringBuffer class. Each operation is connected to 10,000 strings. Date values D1 and D2 are used to determine the time required to complete the operation. Note that when you create a Date object, if there are no arguments, the object is given the current date and time. To calculate how long a connection operation has elapsed, subtract the millisecond representation of the date (using the return value of the GetTime () method). This is a common way to measure JavaScript performance. The results of this test can help you compare the efficiency difference between using the StringBuffer class and using the plus sign.

the results of the previous example run are as follows:

So some people might say that the JavaScript string object does not encapsulate a concat () method, we also use the concat () method below to do the same thing, and enter the following code in Consoel:

Copy Code code as follows:

var D1 = new Date ();
var str = "";
for (Var i=0 i < 10000; i++) {
Str.concat ("text");
}
var d2 = new Date ();

Console.log ("Concatenation with Plus:"
+ (D2.gettime ()-d1.gettime ()) + "milliseconds");


We can see doing 10,000 times character channeling connection it's time consuming is:

It can be concluded that when a certain number of string concatenation is involved, we can improve performance by encapsulating a Java-like StringBuffer object (function) in JavaScript.

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.