Home  >  Article  >  Web Front-end  >  JavaScript中String和StringBuffer的速度之争_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 18:30:50842browse

显示情况时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类的优势仍然很明显。具体在实际中就需要对浏览器进行判断。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn