SoFunction
Updated on 2025-04-09

JavaScript method to implement StringBuffer in Java

This article describes the method of implementing StringBuffer in JavaScript. Share it for your reference. The details are as follows:

The implementation of the Javascript StringBuffer class is to construct a StringBuffer class through prototype, and the code is as follows:

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

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

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

example:

<html>
<head>
<title>test</title>
<script type="text/javascript">
    function StringBuffer() {
      this.__strings__ = new Array();
    }
     = function(str) {
      this.__strings__.push(str);
    };
     = 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();
       ("Sting use time:"+ (date2 - date1) +"ms");

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

I hope this article will be helpful to everyone's JavaScript programming.