The fastest and best way to concatenate HTML strings in javascript

  • 2020-03-30 03:17:28
  • OfStack

The first is to add strings one by one


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.

Second: push one by one into the array


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('') + '';

A little faster than the previous method, but still not good enough...

Third: direct join()


var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '' + arr.join('') + '';

Using a native method (like join()), no matter how it is implemented later, is generally much faster than other methods, and the code is very clean.

Browser performance testing

Each method is tested using an array of length 130, where each element has a variety of lengths, preventing the browser from making special optimizations for strings of a certain length. Each method was tested 1,000 times; The following results show how long it takes to complete the 1000 executions:
< img SRC = "border = 0 / / img.jbzj.com/file_images/article/201406/20146794335457.jpg? 2014579447 ">


Related articles: