日期:2014-05-16  浏览次数:20405 次

关于js中连接字符串效率的测试例子!
分别测试 +=,concat,以及使用array 的join方式,最后在IE6,firefox3.0,safari,chorme发现通过join的方式最快,其次是 +=,最慢的是concat方式。啥也别说了,直接上代码
重要提示,IE6中可能会把浏览器卡死,如果要测试,请把initData中的100000修改一下,似乎1000就可以看到效果了!

<!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=gb2312" />
<title>js</title>
<script>
	var data = initData();

	function initData() {
		var data = [];
		
		for (var i = 0; i++ < 100000;) {
			data.push(randStr());
		}
	
		return data;
	}
	
	function randStr() {
		var strs = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		var result = '';
		var len = 3 + Math.round(22 * Math.random());		//随即生成一个3-25个字符组成的字符串
		for (var i = 0; i++ < len;) {
			result += strs[Math.round(52 * Math.random())];
		}
	
		return result;
	}
	
	function t1() {
		var str = '';
		var last = (new Date()).getTime();
		
		for (var i = 0, d; d = data[i++];) {
			str += d;
		}
	
		$('t1').value = (new Date()).getTime() - last;

		return str;
	}

	function t2() {
		var arr = [];
		var last = (new Date()).getTime();
		
		for (var i = 0, d; d = data[i++];) {
			arr.push(d);
		}
	
		$('t2').value = (new Date()).getTime() - last;

		return arr.join('');
	}

	function t3() {
		var str = '';
		var last = (new Date()).getTime();
		
		for (var i = 0, d; d = data[i++];) {
			str = str.concat(d);
		}
		
		$('t3').value = (new Date()).getTime() - last;

		return str;
	}

	function $() {
		return document.getElementById(arguments[0]);
	}
</script>
</head>
<body>
	<div style="width:400px;margin:40px auto;">
		用时:<input type="text" name="t1" value="" id="t1" readonly/>毫秒
		<input type="button" name="b1" value=" + 连接" onclick="t1()"/>
		<br />
		用时:<input type="text" name="t2" value="" id="t2" readonly/>毫秒
		<input type="button" name="b2" value="join 连接" onclick="t2()"/>
		<br />
		用时:<input type="text" name="t3" value="" id="t3" readonly/>毫秒
		<input type="button" name="b3" value="concact 连接" onclick="t3()"/>
		<br />
	</div>
</body>
</html>