JavaScript如何实现Java的StringBuffer



Javascript StringBuffer类的实现是通过prototype构造一个StringBuffer类,代码如下:


function StringBuffer() {
    
this.__strings__ = new
 Array();
}

StringBuffer.prototype.append 
= function
(str) {
    
this
.__strings__.push(str);
};

StringBuffer.prototype.toString 
= function
() {
    
return this.__strings__.join(""
);
};


例子:

<html>
<head>
<title>test</title>
<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("");
        };

 

       function testStringBuffer(){
              var date1 = new Date();
              var str;
              for( var i=0; i<10000; i++){
                 str += "text";
              }
              var date2 = new Date();
              document.writeln("Sting use time:"+ (date2 - date1) +"ms");

              //StringBuffer
              var date3 = new Date();
             var strBuffer = new StringBuffer();
             for(i=0; i<10000; i++){
                  strBuffer.append("text");
             }
             strBuffer.toString();
             var date4 = new Date();
             document.writeln("<br/>StringBuffer use time:"+ (date4 - date3) +"ms");
       }
</script>
</head>
<body>
      <input type="button" value="testStringBuffer" onclick="testStringBuffer()"/>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/wilsonyun/article/details/43565029