Home > Web Front-end > JS Tutorial > body text

JavaScript method to implement StringBuffer in Java_javascript skills

WBOY
Release: 2016-05-16 16:15:06
Original
1883 people have browsed it

The example in this article describes how JavaScript implements StringBuffer in Java. Share it with everyone for your reference. The details are as follows:

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

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

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

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

Copy after login

Example:

<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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!