The speed contention _javascript skill of string and stringbuffer in JavaScript

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.