javascript做为弱类型的编程语言,并不具备真正的面向对象特性.而在字符串的拼接过程中,每一次+=的操作都伴随着两次对象的初始化和销毁.不仅速度慢,而且效率也不高.通过javascript内置的array对象和prototype属性模拟出StringBuilder类.
//=============================================================================
//class StringBuilder:字符串拼接
//=============================================================================
StringBuilder=function()
{
this.buffer=null;
this.buffer=new Array();
StringBuilder.prototype.Append=function append(string)
{
if((string==null)||(typeof(string)=='undefined'))
{
return;
}
if((typeof(string)=='string')&&(string.length==0))
{
return;
}
this.buffer.push(string);
}
StringBuilder.prototype.AppendLine=function appendLine(string)
{
this.Append(string);
this.buffer.push("/r/n");
}
StringBuilder.prototype.Clear=function clear()
{
if(this.buffer.length>0)
{
this.buffer.splice(0,this.buffer.length);
}
}
StringBuilder.prototype.IsEmpty=function isEmpty()
{
return (this.buffer.length==0);
}
StringBuilder.prototype.ToString=function toString()
{
return this.buffer.join("");
}
}
下面是基于StreamBuilder生成表格的TableBuilder类
//=============================================================================
//class TableBuilder类:生成表格
//=============================================================================
TableBuilder=function(heigth,witdh)
{
this.otable=null;
this.otable=new StringBuilder();
this.otable.Append("<table height="+heigth+" width="+width+">");
TableBuilder.prototype.AppendInnerTD=function appendInnerTD(string)
{
if((string==null)||(typeof(string)=='undefined'))
{
return;
}
if((typeof(string)=='string')&&(string.length==0))
{
return;
}
this.otable.Append("<td>");
this.otable.Append(string);
this.otable.Append("</td>");
}
TableBuilder.prototype.AppendOutTD=function appendOutTD(string)
{
if((string==null)||(typeof(string)=='undefined'))
{
return;
}
if((typeof(string)=='string')&&(string.length==0))
{
return;
}
this.otable.Append(string);
}
TableBuilder.prototype.AppendInnerTR=function appendInnerTR(string)
{
if((string==null)||(typeof(string)=='undefined'))
{
return;
}
if((typeof(string)=='string')&&(string.length==0))
{
return;
}
this.otable.Append("<tr>");
this.otable.Append(string);
this.otable.Append("</tr>");
}
TableBuilder.prototype.AppendOutTR=function appendOutTR(string)
{
if((string==null)||(typeof(string)=='undefined'))
{
return;
}
if((typeof(string)=='string')&&(string.length==0))
{
return;
}
this.otable.Append(string);
}
TableBuilder.prototype.GetTableHtml()
{
this.otable.Append("</table>");
return this.otable;
}
}
修改后拼接字符串的速度可以提高一个数量级.