转贴来自:http://hi.baidu.com/x8online/blog/item/5a3e20d3d1814d013bf3cfce.html
方法:定义一个StringBuffer类,在定义个方法(模拟C#中StringBuilder类)与直接使用连接字符相比
<script type="text/javascript">
function StringBuffer()//使用构造函数
{
this._strings_=new Array;
}
StringBuffer.prototype.append=function (str)//使用原型定义函数属性
{
this._strings_.push(str);
}
StringBuffer.prototype.toString=function ()//使用原型定义函数属性
{
return this._strings_.join("");
}
var buffer=new StringBuffer();//使用类
d1=new Date();
for(var i=0;i<10000;i++)
{
buffer.append("text");
}
var result=buffer.toString();
d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds<br>");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var d1=new Date();
var str="";
for(var i=0;i<10000;i++)
{
str+="text";
}
var d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds");
</script>
结果:Concatenation with StringBuffer:110milliseconds
Concatenation with StringBuffer:2422milliseconds
以上结果经测试正确,结果StringBuffer比直接使用连接字符节省100%~200%的时间