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("");}