javascript模擬dotNet中的StreamBuild及應用

     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;
    } 
}

修改後拼接字符串的速度可以提高一個數量級.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章