Concatenation of strings 1. Most commonly used =
It has always been said that this method is the least efficient. Why? You can take a look at the actual process of this method.
var str = "hello";
str = "world";
(1) Create a string to store "hello".
(2) Create a string to store "world".
(3) Create a string to store the connection result.
(4) Copy the current content of str to the result.
(5) Copy "world" into the result.
(6) Update str so that it points to the result.
Steps 2 to 6 will be executed every time string concatenation is completed, making this operation very resource-consuming. If this process is repeated hundreds, or even thousands, of times, it can cause performance issues. This usage will be abandoned in the future, hahaha. ^_^
2. Join() method
//Button calls
function JoinFn() {
var arr = new Array;
arr[0] = "Zhang San";
arr[1] = "Li Four";
alert(arr.join(""));
}
The steps performed are as follows:
(1) Create a string to store the result.
(2) Copy each string to the appropriate location in the result.
This method is faster than the first one.
3. Encapsulate a custom class
There is no StringBuilder class in JavaScript like in C#, but we can customize a StringBuilder class. The method of building a class is as mentioned in the previous article The "hybrid constructor/prototype approach".
//Customize a StringBuilder class to connect characters String
function StringBuilder() {
this._strings = new Array();
}
StringBuilder.prototype.append = function(str) {
this._strings.push(str) ;
};
StringBuilder.prototype.toString = function() {
return this._strings.join("");
};
//Button calls
function MyConnectClassFn () {
var sb = new StringBuilder();
sb.append("Zhang San");
sb.append("李思");
var strResult = sb.toString( ; It seems that join() is the fastest, but the third one is the slowest. Is there something wrong with my custom StringBuilder class?