Competition for the speed of String and StringBuffer in JavaScript

Source: Internet
Author: User

There is no StringBuffer class in Javascript when the condition is displayed. The implementation of a mainstream Javascript StringBuffer class is to construct a StringBuffer class through prototype.
StringBuffer. js
Copy codeThe Code is 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 codeThe Code is as follows:
<Html>
<Head>
<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>
</Head>
<Body>
<Input type = "button" value = "testStringBuffer" onclick = "testStringBuffer ()"/>
</Body>
</Html>

Now let's test and see what will happen:
IE8:
Sting use time: 11 ms
StringBuffer use time: 47 ms
The result is that the StringBuffer is not more efficient than the String, but is much lower. Did the predecessors make a mistake?
Let's look at it in other browsers:
IE7:
Sting use time: 266 ms
StringBuffer use time: 78 ms
The advantage of StringBuffer in IE7 is obvious.
We can see that in the current mainstream browsers, String connections of the String class are optimized, so the performance is better than the custom StringBuffer class, but in older browsers, the StringBuffer class still has obvious advantages. In practice, you need to judge the browser.

Related Article

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.