Which browser is faster :<

This is a little trick picked up from book "Prctical Javascript DOM Scripting and Ajax Projects".
Only constructs a string that consists of the sring "This is a test string" 10,000 times.

 1 <html>
 2 <head>
 3 <title>Listing 1-2</title>
 4 <script type="text/javascript">
 5 function badTest() {
 6     var startTime = new Date().valueOf();
 7     var s = "";
 8     for (var i = 0; i < 10000; i++) {
 9         s += "This is a test string";
10     }
11     return new Date().valueOf() - startTime;
12 }
13 function goodTest() {
14     var startTime = new Date().valueOf();
15     var stringBuffer = new Array();
16     for (var i = 0; i < 10000; i++) {
17         stringBuffer.push("This is a test string");
18     }
19     var s = stringBuffer.join("");
20     return new Date().valueOf() - startTime;
21 }
22 function betterTest() {
23     var startTime = new Date().valueOf();
24     var stringBuffer = new Array();
25     for (var i = 0; i < 10000; i++) {
26         stringBuffer[stringBuffer.length] = "This is a test string";
27     }
28     var s = stringBuffer.join("");
29     return new Date().valueOf() - startTime;
30 }
31 function doTests() {
32     var htm = "";
33     htm += "Time badTest took: " + badTest() + "<br>";
34     htm += "Time goodTest took: " + goodTest() + "<br>";
35     htm += "Time betterTest took: " + betterTest();
36     document.getElementById("result").innerHTML = htm;
37 }
38 </script>
39 </head>
40 <body>
41 <href="javascript:void(0);" onClick="doTests();">Click here to test</a>
42 <br /><br />
43 <div id="result">&nbsp;</div>
44 </body>
45 </html>

Take a lookat the result:(Amazing)
1. IE 7.0.6000.16512
    Results:

        Time badTest took: 903
        Time goodTest took: 57
        Time betterTest took: 24
2. Firefox 2.0.0.7
    Results:
        Time badTest took: 8
        Time goodTest took: 34
        Time betterTest took: 30
3. Navigator 9.0b3
    Results:
        Time badTest took: 12
        Time goodTest took: 34
        Time betterTest took: 24
4.Opera 9.22
    Results:
        Time badTest took: 5
        Time goodTest took: 17
        Time betterTest took: 12
All browsers do a lot for optimizing their Javascript engine except IE
posted @ 2007-09-24 16:34  David (Dawei) Li  阅读(208)  评论(0编辑  收藏  举报