The fastest and best way to stitch HTML strings in JavaScript _javascript tips

Source: Internet
Author: User

First: adding Strings by string

Copy Code code 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 lowest efficiency! Code logic is relatively complex.

The second type: Push into the array one by one

Copy Code code 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 a little bit quicker than the last one, but it's not good enough ...

The third type: Direct join ()

Copy Code code as follows:

var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...];

var list = ' + Arr.join (') + ';

Using native methods (such as join ()), regardless of how it is implemented later, is generally much faster than other methods, and the code is very concise.

Browser Performance test

Each method is tested with an array of length 130, each of which has a variety of lengths, preventing browsers from making special optimizations to a certain length of string, 1000 tests per method, and the following results: The time required to perform these 1000 times

Related Article

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.