关于 JS的 StringBuffer 和 + 拼接字符串性能的比较 案例 对《JavaScript高级程序设计》在84-85页 的测试

来源:互联网 发布:mac电脑杀毒软件 编辑:程序博客网 时间:2024/05/19 14:34

首先 用JS 自定义 StringBuffer

function StringBuffer(){  this.__strings__ = new Array();   }   StringBuffer.prototype.append = function(str){  this.__strings__.push(str);   };   StringBuffer.prototype.toString = function(){   return this.__strings__.join("");   };

var d1 = new Date();var str = '';for(var i =0 ; i< 1000000;i++){str += "text ";}var d2 = new Date();document.write("Concatenation with plus: " + (d2.getTime()-d1.getTime())+"ms");d1 = new Date();var oBuffer = new StringBuffer();for(var i =0 ; i< 1000000;i++){oBuffer.append("text ");}d2 = new Date();document.write("<br/>Concatenation with StringBuffer: " + (d2.getTime()-d1.getTime())+"ms");


在FF上 显示结果:

Concatenation with plus: 26ms
Concatenation with StringBuffer: 709ms


在Chrome上 显示结果:

Concatenation with plus: 159ms
Concatenation with StringBuffer: 44ms


在IE9上 显示结果:

Concatenation with plus: 379ms
Concatenation with StringBuffer: 83ms


数据有些偏差 但 差距基本上就是这样的。

结论

1.由此可见 FF在+号拼接字符串上性能要优于 StringBuffer 而 IE和chrome 正好相反

2.Chrome JS运行速度 比 FF和IE 都快 而且还不少呢

3.可能是此书出得也有年头了,JS引擎已经发生了变化。

最终结论尽管无论出于代码的可读性还是执行性能考虑,我们都应该使用加号拼接字符串,然而,使用数组对于IE6、7的提升是如此的巨大以至于最为保守折中的做法仍然是使用数组,因为相对于IE6、7的提升,其他浏览器用加号的做法带来的提升甚至可以忽略不计。