The fastest and best way to splice HTML strings in javascript

Source: Internet
Author: User

First: Add strings one by one

Copy codeThe Code 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 most efficient! The Code logic is relatively complex.

Type 2: push the data to the array one by one

Copy codeThe Code 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 is a little faster than the previous method, but it is not good enough...

Third: Direct join ()

Copy codeThe Code is as follows:
Var arr = ['item 1', 'item 2', 'item 3',...];

Var list = ''+ arr. join ('') + '';

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

Browser Performance Testing

Each method uses an array with a length of 130 for testing. The length of each element is varied to prevent the browser from making special Optimizations to strings of a certain length; each method is tested for 1000 times. The following results show the time required to perform the 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.