Comparison of String splicing efficiency using Javascript: String. replace VS Array. push

Source: Internet
Author: User

/*** Background: I found that my colleagues like to use a template (String. replace) to spell JS strings. That's right. Using a template increases readability,
* Compared with the efficient Array. push and then Array. join ("") concatenate strings, replace can be a problem.
* For example, the number of loops is 1000. The gap in ie is large, and the Array. push in ff is nearly doubled. Run the following demo:
* String. replace VS Array. push */var testType = 2; // 1 = String. replace or 2 = Array. push var s = "", sArr = [], n = 1000; // u can change "n" from 1000 to limit for (var I = 0; I <n; I ++) {s + = "{a}";} var t1 = new Date (). getTime (); for (var I = 0; I <n; I ++) {if (testType = 1) s = s. replace ("{a}", "ba"); else sArr. push ("B" + "a");} if (testType! = 1) s = sArr. join (""); var t2 = new Date (). getTime (); alert ("use" + (testType = 1? "String. replace": "Array. push") + ":" + (t2-t1) + "ms ")

The other conclusion is that over 100 ms (which number does it look like ?) Latency can be perceived. If the processing speed of the template scheme is slow (because the template needs to be read first), latency can be perceived and is not allowed in some projects.

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.