提高js字符串连接的性能
2008-05-19 10:47
274 查看
转贴来自:http://hi.baidu.com/x8online/blog/item/5a3e20d3d1814d013bf3cfce.html
方法:定义一个StringBuffer类,在定义个方法(模拟C#中StringBuilder类)与直接使用连接字符相比
<script type="text/javascript">
function StringBuffer()//使用构造函数
{
this._strings_=new Array;
}
StringBuffer.prototype.append=function (str)//使用原型定义函数属性
{
this._strings_.push(str);
}
StringBuffer.prototype.toString=function ()//使用原型定义函数属性
{
return this._strings_.join("");
}
var buffer=new StringBuffer();//使用类
d1=new Date();
for(var i=0;i<10000;i++)
{
buffer.append("text");
}
var result=buffer.toString();
d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds<br>");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var d1=new Date();
var str="";
for(var i=0;i<10000;i++)
{
str+="text";
}
var d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds");
</script>
结果:Concatenation with StringBuffer:110milliseconds
Concatenation with StringBuffer:2422milliseconds
以上结果经测试正确,结果StringBuffer比直接使用连接字符节省100%~200%的时间
方法:定义一个StringBuffer类,在定义个方法(模拟C#中StringBuilder类)与直接使用连接字符相比
<script type="text/javascript">
function StringBuffer()//使用构造函数
{
this._strings_=new Array;
}
StringBuffer.prototype.append=function (str)//使用原型定义函数属性
{
this._strings_.push(str);
}
StringBuffer.prototype.toString=function ()//使用原型定义函数属性
{
return this._strings_.join("");
}
var buffer=new StringBuffer();//使用类
d1=new Date();
for(var i=0;i<10000;i++)
{
buffer.append("text");
}
var result=buffer.toString();
d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds<br>");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var d1=new Date();
var str="";
for(var i=0;i<10000;i++)
{
str+="text";
}
var d2=new Date();
document.write ("<br>Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds");
</script>
结果:Concatenation with StringBuffer:110milliseconds
Concatenation with StringBuffer:2422milliseconds
以上结果经测试正确,结果StringBuffer比直接使用连接字符节省100%~200%的时间
相关文章推荐
- JS中三种字符串连接方式及其性能比较
- JS 字符串连接[性能比较]
- 数组方法解决JS字符串连接性能问题有争议
- 浅谈JS中的三种字符串连接方式及其性能比较
- 从一道编程题看JS字符串连接性能
- 数组方法解决JS字符串连接性能问题有争议
- 不要使用连接来合并多个字符串,应该使用StringBuilder来提高性能
- JS中三种字符串连接方式及其性能比较
- JS中三种字符串连接方式及其性能比较
- JS 字符串连接[性能比较]
- [转载]PayPal为什么从Java迁移到Node.js,性能提高一倍,文件代码减少44%
- 转发:关于javascript字符串连接性能
- 将CSS放头部,JS放底部,可以提高页面的性能的原因
- 提高HTTP的连接性能
- 什么情况下用+运算符进行字符串连接比调用StringBuffer/StringBuilder对象的append方法连接字符串性能更好?
- 当心字符串连接的性能
- 教你50招提升ASP.NET性能(二十三):StringBuilder不适用于所有字符串连接的场景;String.Join可能是
- 你不得不知道的关于JavaScript 中字符串连接的性能问题
- 利用JS提高组合拼接字符串效率的方法
- 提高代码性能,写出高质量js/jq代码常记