就像在c#中一样,我们可以使用”+”来拼接字符串,而对于操作频繁、讲究效率的字符串拼接操作我们应该选择stringbuilder类。在javascript中是否也存在这个问题呢?答案是肯定的,虽然javascript并没有为我们提供一个内置的stringbuilder对象,但是我们可以自己来创建一个!至于效率到底能提高多少,让程序说话吧!
//---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用时:" + (d2.gettime() - d1.gettime()) + ""); //---+-----var d3 = new date();var str = "";for(var i = 1; i < 10000; i++){str += "e3card";}var d4 = new date();document.write("+链接用时:" + (d4.gettime() - d3.gettime()) + "");
在我的机器上(core2 3.0g/4gram),反复f5后得到一个,比较平稳的测试结果:
stringbuilder用时:32
+链接用时:1109哇哦,30多倍,我没看错吧!
好了,赶快自己做好一个lib,以后都用这个stringbuilder吧:
function stringbuilder(){this.__string__ = new array();}stringbuilder.prototype.append = function(str){this.__string__.push(str);}stringbuilder.prototype.tostring = function(){return this.__string__.join("");}