Javascript simulation C # stringbuilder

Source: Internet
Author: User

Just like in C #, we can use "+" to concatenate strings. For String concatenation operations that are frequent and efficient, we should select the stringbuilder class. Does this problem also exist in JavaScript? The answer is yes. Although JavaScript does not provide us with a built-in stringbuilder object, we can create one by ourselves! Let the program talk about how much efficiency can be improved!

// --- Stringbuilder --- function stringbuilder () {This. _ string _ = new array ();} stringbuilder. prototype. append = function (STR) {This. _ string __. push (STR);} stringbuilder. prototype. tostring = function () {return this. _ string __. join ("");} var d1 = new date (); var buffer = new stringbuilder (); For (VAR I = 1; I <10000; I ++) {buffer. append ("e3card");} var strresult = buffer. tostring (); var D2 = new date (); document. write ("stringbuilder time:" + (d2.gettime ()-d1.gettime () + "<br/>"); // --- + ----- var D3 = new date (); vaR STR = ""; for (VAR I = 1; I <10000; I ++) {STR + = "e3card";} var D4 = new date (); document. write ("+ link time:" + (d4.gettime ()-d3.gettime () + "<br/> ");

On my machine (core2 3.0g/4 gram), I got a stable test result after repeating F5:

Stringbuilder time: 32
+ Link time: 1109

Wow, it's more than 30 times. I'm right!

Now, make a lib by yourself and use this stringbuilder later:

function stringbuilder(){this.__string__ = new array();}stringbuilder.prototype.append = function(str){this.__string__.push(str);}stringbuilder.prototype.tostring = function(){return this.__string__.join("");}

 

 

 

 

 

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.