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

(编辑:jimmy 日期: 2024/10/10 浏览:2)

复制代码 代码如下:
<!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>
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。