Code
/**
* @author wenjl
* @desc string连接类
* @createTime 2009-03-29
*/
function StringBuilder(){
this.__string__ = new Array();
}
StringBuilder.prototype.append = function(str){
this.__string__.push(str);
}
StringBuilder.prototype.toString = function(){
return this.__string__.join("");
}
/**
* @author wenjl
* @desc string连接类
* @createTime 2009-03-29
*/
function StringBuilder(){
this.__string__ = new Array();
}
StringBuilder.prototype.append = function(str){
this.__string__.push(str);
}
StringBuilder.prototype.toString = function(){
return this.__string__.join("");
}
上面是类似C#StringBuilder类.
下面是我的测试代码
Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="StringBuilder.js">
</script>
<script type="text/javascript">
var d1 = new Date();
var buffer = new StringBuilder();
for (var i = 1; i < 10000; i++) {
buffer.append("E3Card");
}
var strResult = buffer.toString();
var d2 = new Date();
document.write("StringBuilder用时:" + (d2.getTime() - d1.getTime()) + "<br/>");
//---+-----
var d3 = new Date();
var str = "";
for (var i = 1; i < 10000; i++) {
str += "E3Card";
}
var d4 = new Date();
document.write("+链接用时:" + (d4.getTime() - d3.getTime()) + "<br/>");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="StringBuilder.js">
</script>
<script type="text/javascript">
var d1 = new Date();
var buffer = new StringBuilder();
for (var i = 1; i < 10000; i++) {
buffer.append("E3Card");
}
var strResult = buffer.toString();
var d2 = new Date();
document.write("StringBuilder用时:" + (d2.getTime() - d1.getTime()) + "<br/>");
//---+-----
var d3 = new Date();
var str = "";
for (var i = 1; i < 10000; i++) {
str += "E3Card";
}
var d4 = new Date();
document.write("+链接用时:" + (d4.getTime() - d3.getTime()) + "<br/>");
</script>
</head>
<body>
</body>
</html>
测试结果:
火狐:
StringBuilder用时:63
+链接用时:31
IE 7:
StringBuilder用时:78
+链接用时:1532
IE 8:
StringBuilder用时:16
+链接用时:31
上面的结果大家可以看出来在IE和火狐下两个方法的巨大差异,奇怪的是在火狐里+号的速度竟然比StringBuilder快.