js switch与elseif做浏览器执行速度对比

<script type="text/javascript">
	var count,n;
	var startTimeSwitch = new Date().getTime();
	count = 10000;
	sum = count;
	n = 9;
	while (sum>0) {
		switch (n) {
			case 1 :
				sum--;
				break;
			case 2 :
				sum--;
				break;
			case 3 :
				sum--;
				break;
			case 4 :
				sum--;
				break;
			case 5 :
				sum--;
				break;
			case 6 :
				sum--;
				break;
			case 7 :
				sum--;
				break;
			case 8 :
				sum--;
				break;
			case 9 :
				sum--;
				break;
			case 10 :
				sum--;
				break;
			default :
				sum--;
				break;
		}
	}
	var endTimeSwitch = new Date().getTime();
	var startTimeElseIf = new Date().getTime();
	sum = count;
	while(sum>0){
		if (n == 1) {
			sum--;
		}else if (n == 2) {
			sum--;
		}else if (n == 3) {
			sum--;
		}else if (n == 4) {
			sum--;
		}else if (n == 5) {
			sum--;
		}else if (n == 6) {
			sum--;
		}else if (n == 7) {
			sum--;
		}else if (n == 8) {
			sum--;
		}else if (n == 9) {
			sum--;
		}else if (n == 10) {
			sum--;
		}else {
			sum--;
		}
	}
	var endTimeElseIf = new Date().getTime();
	alert("switch共用时:"+(endTimeSwitch-startTimeSwitch)+"毫秒---elseif共用时:"+(endTimeElseIf-startTimeElseIf)+"毫秒");
</script>


count IE9(毫秒)switch/elseif FireFox-v10.2(毫秒)switch/elseif chrome-v19(毫秒)switch/elseif
100 0/0 1/1 0/0
1000 0/0 1/1 0/0
10000 0/0 2/1 0/2
100000 1/3 2/2 4/1
1000000 17/20 5/13 15/10
10000000 108/119 16/85 86/52
100000000 974/1156 261/838 637/516
1000000000 9028/12918 2553/8669 6164/5483


测试结果很意外,chrome对switch与elseif执行速度几乎持平,在chrome下使用elseif会更好些。

你可能感兴趣的:(JavaScript)