There is no StringBuffer class in JavaScript when the situation is displayed, and a mainstream JavaScript StringBuffer class is implemented by prototype to construct a StringBuffer class.
Stringbuffer.js
Copy Code code as follows:
function StringBuffer () {
This.content = new Array;
}
StringBuffer.prototype.append = function (str) {
This.content.push (str);
}
StringBuffer.prototype.toString = function () {
Return This.content.join ("");
}
Now let's write a test case:
teststringbuffer.html
Copy Code code as follows:
<title>test</title>
<script type= "Text/javascript" language= "JavaScript" src= "Stringbuffer.js" ></script>
<script>
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");
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>
<body>
<input type= "button" value= "Teststringbuffer" onclick= "Teststringbuffer ()"/>
</body>
Now let's take a test and see what happens:
IE8:
Sting Use time:11ms
StringBuffer Use Time:47ms
The result is that StringBuffer is not only more efficient than string, but a lot lower. Is it that the seniors are wrong?
So let's look in another browser:
IE7:
Sting Use Time:266ms
StringBuffer Use time:78ms
The advantages of StringBuffer in IE7 are obvious.
As you can see, the string concatenation of the string class is optimized in the current mainstream browsers, so performance is better than the custom StringBuffer class, but the advantages of the StringBuffer class are still evident in older browsers. Specifically in the actual need to judge the browser.