Maison > interface Web > js tutoriel > le corps du texte

JavaScript中String和StringBuffer的速度之争_javascript技巧

WBOY
Libérer: 2016-05-16 18:30:50
original
842 Les gens l'ont consulté

显示情况时Javascript中并没有StringBuffer类,一种主流的Javascript StringBuffer类的实现是通过prototype构造一个StringBuffer类。
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
复制代码 代码如下:



test

<script> <BR>function testStringBuffer(){ <BR>var date1 = new Date(); <BR>var str; <BR>for( var i=0; i<10000; i++){ <BR>str += "text"; <BR>} <BR>var date2 = new Date(); <BR>document.writeln("Sting use time:"+ (date2 - date1) +"ms"); <BR>var date3 = new Date(); <BR>var strBuffer = new StringBuffer(); <BR>for(i=0; i<10000; i++){ <BR>strBuffer.append("text"); <BR>} <BR>strBuffer.toString(); <BR>var date4 = new Date(); <BR>document.writeln("<br/>StringBuffer use time:"+ (date4 - date3) +"ms"); <BR>} <BR></script>






现在让我们来测试下,看看会有什么发生:
IE8:
Sting use time:11ms
StringBuffer use time:47ms
结果是StringBuffer不但没有比String效率高,反而使低了不少。难道是前辈们错了?
那让我们再在别的浏览器中看看吧:
IE7:
Sting use time:266ms
StringBuffer use time:78ms
IE7中StringBuffer的优势很明显。
可以看到,在现在的主流浏览器中,都对String类的字符串连接作了优化,所以性能要好于自定义的StringBuffer类,但是在比较老的浏览器中,StringBuffer类的优势仍然很明显。具体在实际中就需要对浏览器进行判断。
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!