2011年9月29日 星期四

[轉錄] PHP - if v.s. switch 誰快?

fluffycat 上看到一篇測試 PHP 的 if 和 switch 判斷式哪個執行速度較快,根據作者使用亂數測試的結果是 if 略勝 switch,但差距並不明顯。雖然程式碼亂數只取到 5,但下面有網友幫忙測試了亂數 10、20 和 50,得到的結果還是 if 略勝。

小小的測試,小小的趣味。

原始碼:下載

//copyright Lawrence Truett and FluffyCat.com 2009, all rights reserved
  	define('BR', '<'.'BR'.'>');
	echo 'Performance Testing PHP if / else VS switch with 100,000 iterations'.BR.BR;
	
	$ifTime = 0;
	$switchTime = 0;
	for ($x = 0; $x < 100000; $x++) {
		$oneToFive = rand(1,5);
		if (0 == fmod($x,2)) {
			$switchTime = $switchTime + testSwitch($oneToFive);
			$ifTime = $ifTime + testIf($oneToFive);
		} else {
			$ifTime = $ifTime + testIf($oneToFive);  			
			$switchTime = $switchTime + testSwitch($oneToFive);  		
		}
	}
	echo 'total if / else time: '.$ifTime.BR;
	echo 'total case time: '.$switchTime.BR;
	echo BR;
	if ($ifTime > $switchTime) {
		echo 'switch is quicker by '.($ifTime - $switchTime).BR;
	} else {
		echo 'if / else is quicker by '.($switchTime - $ifTime).BR;		
	}


	function testSwitch($oneToFive) {
		$time_start = microtime(true);
		switch($oneToFive) {
			case 1: $z = 1; break;
			case 2: $z = 2; break;
			case 3: $z = 3; break;
			case 4: $z = 4; break;
			case 5: $z = 5; break;						
		}
		$time_end = microtime(true);
		$time = $time_end - $time_start;
		return $time;
	}
  
	function testIf($oneToFive) {
		$time_start = microtime(true);
		if (1 == $oneToFive) {
			$z = 1;
		} elseif(2 == $oneToFive) {
			$z = 2;			
		} elseif(3 == $oneToFive) {
			$z = 3;	
		} elseif(4 == $oneToFive) {
			$z = 4;	
		} elseif(5 == $oneToFive) {
			$z = 5;	
		}
		$time_end = microtime(true);
		$time = $time_end - $time_start;
		return $time;
	}



參考資料:http://www.fluffycat.com/PHP-Design-Patterns/PHP-Performance-Tuning-if-VS-switch/


沒有留言: