DIV CSS 佈局教程網

JavaScript 中 String 與 StringBuffer 效能之爭
編輯:關於JavaScript     

JavaScript 本身並沒有像 Java 那樣的 StringBuffer 類別,因此社群裡常見的做法是透過 prototype 自行打造一個。先看這個經典實作:

StringBuffer.js


複製程式碼 程式碼如下:
function StringBuffer(){
this.content = new Array;
}
StringBuffer.prototype.append = function( str ){
this.content.push( str );
}
StringBuffer.prototype.toString = function(){
return this.content.join("");
}

接著我們寫一個測試來比較兩者的效能:

TestStringBUffer.html


複製程式碼 程式碼如下:
<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>

實測結果相當有意思。在 IE8 上:

Sting use time:11ms
StringBuffer use time:47ms

StringBuffer 不但沒有更快,反而慢了不少。難道是前輩們的經驗過時了?換個瀏覽器再看:

IE7:
Sting use time:266ms
StringBuffer use time:78ms

在 IE7 中,StringBuffer 的優勢就很明顯了。

結論是:現代主流瀏覽器都已對字串串接做了優化,直接串接反而比自製的 StringBuffer 更快;但在較舊的瀏覽器裡,StringBuffer 的效能優勢依然存在。因此實務上若要兼顧,就需要針對瀏覽器版本做判斷與取捨。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved