顯示具有 PHP 標籤的文章。 顯示所有文章
顯示具有 PHP 標籤的文章。 顯示所有文章

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/


2011年9月28日 星期三

PHP 5.4 beta1 發佈

PHP 5.4 beta1 發佈了!!!

增加了一些新功能和移除部分過時的行為,主要做了三項變動:

  1. 增加可呼叫的 type hint。
  2. 移除自動辨識時區演算法,改用 UTC 為預設。
  3. 使用 mysqlnd 為預設來取代掉 mysql、mysqli 和 pdo_mysql。


原文:

  • Added callable typehint.
  • Removed the timezone guessing algorithm. "UTC" is now used in case the timezone is not set.
  • The mysql, mysqli and pdo_mysql extensions now use mysqlnd by default.

參考資料:http://www.php.net/archive/2011.php#id2011-09-27-1