利用数组提高IE拼接字符串效率

今天终于静下心来研究程序的效率问题,竟然发现一个普通的循环拼接字符串在IE下竟然执行了3秒钟时间
搜索发现早就有人对此进行了研究,于是又学到了一招,就是利用数组的join方法
以后得注意着这个问题,当需要拼接的字符串比较多的时候使用如下方法:

  1. function StringBuffer(){
  2.     this._strings = new Array();
  3. }
  4.  
  5. StringBuffer.prototype.append = function(str){
  6.     this._strings.push(str);
  7. };
  8. StringBuffer.prototype.toString = function(){
  9.     var str = arguments.length == 0 ? '' : arguments[0];
  10.     return this._strings.join(str);
  11. };
  12.  
  13. //示例
  14. var buffer = new StringBuffer();
  15. buffer.append('This is ');
  16. buffer.append('an ');
  17. buffer.append('example!');
  18. alert(buffer.toString());

在我的代码上实际使用时,原来需要执行3秒多的代码只要600多毫秒就搞定了,一举解决了速度问题
另外arguments对象可以在某些场合派上用场

17fav 收藏本文
标签:, , , , , ,

相关日志 随机文章

Comments

2 Responses to “利用数组提高IE拼接字符串效率”

  1. 南子 on 2008-07-31 10:01 pm

    强啊!

    [Reply]

  2. bianbian on 2008-08-16 5:29 pm

    弱啊。。。不过firefox没有直接+快

    [Reply]

Leave a Reply




请输入验证码

Use "<coolcode></coolcode>" to publish your code.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.

京ICP备05059555号

收藏 & 分享

Powered by 17fav.com