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

2019-12-25,,,

复制代码 代码如下:
<!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>

您可能感兴趣的文章:

  • JS扩展String.prototype.format字符串拼接的功能
  • JavaScript实现格式化字符串函数String.format
  • JS 对象(Object)和字符串(String)互转方法
  • JSON的String字符串与Java的List列表对象的相互转换
  • String字符串匹配javascript 正则表达式
  • JavaScript截取字符串的Slice、Substring、Substr函数详解和比较
  • js substring()字符串截取函数
  • JavaScript字符串String和Array操作的有趣方法
  • JS 截取字符串substr 和 substring方法的区别
  • js最实用string(字符串)类型的使用及截取与拼接详解

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

下载本文的Word格式文档,以方便收藏与打印。