比str+=str;高效的字符串连接方法

Posted on 2008-6-5 星期四

在javascript编程中经常要连接字符串,很多人都习惯用:

  1. var str=“hello”;
  2. str+=“world”;

这种操作在JS中要经过6个步骤,非常耗资源:
(1) 创建存储”hello”的字符串.
(2) 创建存储”world”的字符串.
(3) 创建存储连接结果的字符串.
(4) 把str的当前内容复制到结果中.
(5) 把”world”复制到结果中.
(6) 更新str,使它指向结果.

解决方法就是用array对象来连接字符串:

  1. var arr = new Array;
  2. arr[0] = “hello”;
  3. arr[1] = “world”;
  4. var str = arr.join(“”);

执行只需两步,
(1) 创建存储结果的字符串.
(2) 把每个字符串复制到结果中的合适位置.

下面为了方便使用,给出了一个字符串连接类:

  1. function SGen(){this._str_ = new Array;};
  2. SGen.prototype.add = function (str){this._str_.push(str);};
  3. SGen.prototype.toString = function (){return this._str_.join(“”);};
  4.  
  5. var buffer = new SGen();
  6. buffer.add(“hello “);
  7. buffer.add(“world”);
  8. var result = buffer.toString();
  9. buffer = null;

No comments have been added to this post yet.

留下评论

(必需)

(必需)


Information for comment users
Line and paragraph breaks are implemented automatically. Your e-mail address is never displayed. Please consider what you're posting.

Use the buttons below to customise your comment.


RSS feed for comments on this post | TrackBack URI