The first type: add string by string
The code copy is as follows:
var arr = ['item 1', 'item 2', 'item 3', ...];
list = '';
for (var i = 0,
l = arr.length; i < l; i++) {
list += '' + arr[i] + '';
}
list = '' + list + '';
This is the most common, but the least efficient! The code logic is relatively complex.
The second type: push into the array one by one
The code copy is as follows:
var arr = ['item 1', 'item 2', 'item 3', ...],
list = [];
for (var i = 0,
l = arr.length; i < l; i++) {
list[list.length] = '' + arr[i] + '';
}
list = '' + list.join('') + '';
It's slightly faster than the previous method, but it's still not good enough...
The third type: direct join()
The code copy is as follows:
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '' + arr.join('') + '';
Use native methods (such as join()), no matter how it is implemented later, it is generally much faster than other methods, and the code is very concise.
Browser performance testing
Each method is to use an array of length 130 to test, where each element has a variety of lengths to prevent the browser from making special optimizations for strings of a certain length; each method was tested 1,000 times; the following results show that it takes to execute these 1,000 times: