JavaScript 利用StringBuffer类提升+=拼接字符串效率

复制代码 代码如下:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title></title>

  </head>

  <body>

  </body>

  <script type="text/javascript"><!--

  var str = 'hello';

  str += 'world';

  //每次完成字符串连接都会执行步骤2到6步

  //实际上,这段代码在幕后执行的步骤如下:

  /**//*

  1.创建存储'hello'的字符串

  2.创建存储'world'的字符串

  3.创建存储链接结果的字符串

  4.把str的当前内容复制到结果中

  5.把'world'复制到结果中

  6.更新str,使它指向结果

  */

  //为了提高性能最好使用数组方法拼接字符串

  //创建一个StringBuffer类

  function StringBuffer(){

  this.__strings__ = [];

  };

  StringBuffer.prototype.append = function(str){

  this.__strings__.push(str);

  };

  StringBuffer.prototype.toString = function(){

  return this.__strings__.join('');

  };

  //调用StringBuffer类,实现拼接字符串

  //每次完成字符串连接都会执行步骤2步

  //实际上,这段代码在幕后执行的步骤如下:

  /**//*

  1.创建存储结果的字符串

  2.把每个字符串复制到结果中的合适位置

  */

  var buffer = new StringBuffer();

  buffer.append('hello ');

  buffer.append('world');

  var result = buffer.toString();

  //用StringBuffer类比使用+=节省50%~66%的时间

  //-->

  </script>

  </html>