65.9K
CodeProject 正在变化。 阅读更多。
Home

JStringBuilder

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (11投票s)

2006年11月14日

1分钟阅读

viewsIcon

38154

downloadIcon

117

模拟 JavaScript 中的 C# StringBuilder 类。

引言

我编写这段代码是因为我需要在 JavaScript 中使用一个与 C# Stringbuilder 类相似的类。在字符串连接方面,Internet Explorer 非常糟糕。如果你曾经尝试过使用 a=a+"string"; 循环代码,那你就会明白我的意思了。其他浏览器似乎运行良好。我不确定 IE 在后台在做什么。IE 似乎针对数组进行了优化。因此,我在 JavaScript 中构建了一个包装器,模拟了 stringbuilder 类。我尝试在大小限制范围内(保持 1.1KB 的脚本大小)包含尽可能多的原始 stringbuilder 方法。我还构建了一个测试套件来查看实际的时间节省。测试是循环 10,000 次,将字符串连接在一起。string 对象产生的结果是:构建和渲染需要 2.34 秒。StringBuilder 类产生的结果是:0.187 秒。哇!多么大的改进。但是 Firefox 中的测试结果几乎相同。这帮助我得出结论,IE 对 JavaScript 字符串连接的处理不太好。如果将测试套件推到 100,000 次迭代,字符串似乎无法完成。随着 AJAX 的主流化,越来越多的公司正在重新思考客户端/服务器端处理。为什么不利用客户端处理器来管理数据组织呢?嗯,在我看来,一切都应该平衡,就像吃东西一样。如果你保持均衡的饮食,你就会非常健康。编码也不例外。希望未来应用程序和 Web 将会平等。

文档化的源代码

/*
    ##################### DO NOT MODIFY THIS HEADER #####################
    #                                                                   #
    # Title: JStringBuilder Class                                       #
    # Description: Simulates the C# StringBuilder Class in Javascript.  #
    # Website: www.codevendor.com                                       #
    # Author: Adam Smith                                                #
    # Email: ibulwark@hotmail.com                                       #
    # Date: November 12, 2006                                           #
    #                                                                   #
    # ----------------------------------------------------------------- #
    #                                                                   #
    # Version 1.1: Added AppendFormat Function and ReplaceThis Function #
    # Date Released: Feb 27,2007                                        #
    #                                                                   #
    # Version 1.0: JStringBuilder Class Released                        #
    # Date Released: Nov 12, 2006                                       #
    #                                                                   #
    #####################################################################
*/

// Simulates the C# StringBuilder Class in Javascript.
// Parameter["stringToAdd"] - The string to add.
StringBuilder = function(stringToAdd)
{
    var h = new Array();
    if(stringToAdd){h[0] = stringToAdd;}
    this.Append = Append;
    this.AppendLine = AppendLine;
    this.AppendFormat = AppendFormat;
    this.ToString = ToString;
    this.Clear = Clear;
    this.Length = Length;
    this.Replace = Replace;
    this.Remove = Remove;
    this.Insert = Insert;
    this.GetType = GetType;


    // Appends the string representation of a specified object to the end 
    // of this instance.
    // Parameter["stringToAppend"] - The string to append.
    function Append(stringToAppend)
    {
        h[h.length] = stringToAppend;
    }

    // Appends the string representation of a specified object to the end 
    // of this instance with a carriage return and line feed.
    // Parameter["stringToAppend"] - The string to append.
    function AppendLine(stringToAppend)
    {
        h[h.length] = stringToAppend;
        h[h.length] = "\r\n";
    }

    // Converts a StringBuilder to a String.
    function ToString()
    {
        if(!h){ return ""; }
        if(h.length<2){ return (h[0])?h[0]:""; }
        var a = h.join('');
        h = new Array();
        h[0] = a;
        return a;
    }

    // Clears the StringBuilder
    function Clear()
    {
        h = new Array();
    }

    // Gets the StringBuilder Length
    function Length()
    {
        if(!h){return 0;}
        if(h.length<2){ return (h[0])?h[0].length:0; }
        var a = h.join('');
        h = new Array();
        h[0] = a;
        return a.length;
    }

    // Replaces all occurrences of a specified character or string 
    // in this instance with another specified character or string.
    // Parameter["oldValue"] - The string to replace.
    // Parameter["newValue"] - The string that replaces oldValue.
    // Parameter["caseSensitive"] - True or false for case replace.
    // Return Value - A reference to this instance with all instances of 
    // oldValue replaced by newValue.
    function Replace(oldValue, newValue, caseSensitive)
    {
    var b = ReplaceThis(h.join(''), oldValue, newValue, caseSensitive);
        h = new Array();
        h[0] = b;
        return this;
    }

    // Removes the specified range of characters from this instance.
    // Parameter["startIndex"] - The position where removal begins.
    // Parameter["length"] - The number of characters to remove.
    // Return Value - A reference to this instance after the excise 
    // operation has occurred.
    function Remove(startIndex, length)
    {
        var s = h.join('');
        h = new Array();

        if(startIndex<1){h[0]=s.substring(length, s.length);}
        if(startIndex>s.length){h[0]=s;}
        else
        {
            h[0]=s.substring(0, startIndex);
            h[1]=s.substring(startIndex+length, s.length);
        }

        return this;
    }

    // Inserts the string representation of a specified object into 
    // this instance at a specified character position.
    // Parameter["index"] - The position at which to insert.
    // Parameter["value"] - The string to insert.
    // Return Value - A reference to this instance after the insert 
    // operation has occurred.
    function Insert(index, value)
    {
        var s = h.join('');
        h = new Array();

        if(index<1){h[0]=value; h[1]=s;}
        if(index>=s.length){h[0]=s; h[1]=value;}
        else
        {
            h[0]=s.substring(0, index);
            h[1]=value;
            h[2]=s.substring(index, s.length);
        }

        return this;
    }

    // Gets the type
    function GetType()
    {
        return "StringBuilder";
    }

    //Replaces a string with a string
    function ReplaceThis(_WhatToCheck, _FindThis, _ReplaceWith, _CaseSense)
    {
        if(_WhatToCheck==undefined || _WhatToCheck==""){return "";}
        var r=new RegExp(_FindThis,(_CaseSense==true)?'g':'gi');
        return _WhatToCheck.replace(r, _ReplaceWith);
    }

    //Appends a formatted string
    function AppendFormat(format, arg0)
    {
    for (var i = 1; i < arguments.length; i++)
        {
          format = ReplaceThis(format, "\\{" + (i-1) + "\\}", 
                        arguments[i], true)
        }
        Append(format);
    }
};

压缩的源代码 (1.1 KB)

StringBuilder=function(A){var h=new Array();if(A){h[0]=A;}this.Append=Append;
this.AppendLine=AppendLine;this.AppendFormat=AppendFormat;
this.ToString=ToString;this.Clear=Clear;this.Length=Length;
this.Replace=Replace;this.Remove=Remove;this.Insert=Insert;
this.GetType=GetType;function Append(s){h[h.length]=s;}
function AppendLine(s){h[h.length]=s;h[h.length]="\r\n";}function ToString()
{if(!h){return "";}if(h.length<2){return (h[0])?h[0]:"";}var a=h.join('');
h=new Array();h[0]=a;return a;}function Clear(){h=new Array();}
function Length(){if(!h){return 0;}if(h.length<2){return (h[0])?h[0].length:0;}
var a=h.join('');h=new Array();h[0]=a;return a.length;}function Replace(o,n,c)
{var b=ReplaceThis(h.join(''),o,n,c);h=new Array();h[0]=b;return this;}
function Remove(i,l){var s=h.join('');h=new Array();if(i<1){h[0]=s.substring
(l,s.length);}if(i>s.length){h[0]=s;}else{h[0]=s.substring(0,i);
h[1]=s.substring(i+l,s.length);}return this;}function Insert(i,v)
{var s=h.join('');h=new Array();if(i<1){h[0]=v;h[1]=s;}if(i>=s.length){h[0]=s;
h[1]=v;}else{h[0]=s.substring(0,i);h[1]=v;h[2]=s.substring(i,s.length);}
return this;}function GetType(){return "StringBuilder";}
function ReplaceThis(W,F,R,C){if(W==undefined||W==""){return "";} 
var r=new RegExp(F,(C==true)?'g':'gi');return W.replace(r,R);}
function AppendFormat(F,A){for(var i=1;i<arguments.length;i++)
{F=ReplaceThis(F,"\\{" + (i-1) + "\\}",arguments[i],true)}Append(F);}};

版本

  • 版本 1.1:添加了 AppendFormat 函数和 ReplaceThis 函数
    发布日期:2007 年 2 月 27 日
  • 版本 1.0:发布了 JStringBuilder
    发布日期:2006 年 11 月 12 日
© . All rights reserved.