当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 利用StringBuffer类提升+=拼接字符串效率

Javascript
[IE&FireFox兼容]JS对select操作
JS实现全景图效果360度旋转
Unicode 编码转换器
如何用javascript判断录入的日期是否合法
图片从右至左滚动JS
JS控件autocomplete 0.11演示及下载 1月5日已更新
一个对于js this关键字的问题
Javascript标准DOM Range操作全集
兼容Mozilla必须知道的知识。
你所要知道JS(DHTML)中的一些技巧
JS效率个人经验谈(8-15更新),加入range技巧
如何让动态插入的javascript脚本代码跑起来。
Javascript调试工具(下载)
脚本中出现 window.open() access is denied - 拒绝访问 情况一则及分析
Javascript-Mozilla和IE中的一个函数直接量的问题
贴一个在Mozilla中常用的Javascript代码
Javascript miscellanea -display data real time, using window.status
js技巧--转义符"\"的妙用
In Javascript Class, how to call the prototype method.(three method)
Javascript与vbscript数据共享

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 272 ::
收藏到网摘: n/a

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>